将 WebClient JSON-RPC 调用迁移到 C# 中的 HttpClient

Migrate WebClient JSON-RPC calls to HttpClient in C#

我想在 .Net 6 中使用 HttpClient 完成与此相同的事情

using (var webClient = new WebClient())
{
  // Required to prevent HTTP 401: Unauthorized messages
  webClient.Credentials = new NetworkCredential(username, password);
  // API Doc: http://kodi.wiki/view/JSON-RPC_API/v6
  var json = "{\"jsonrpc\":\"2.0\",\"method\":\"GUI.ShowNotification\",\"params\":{\"title\":\"This is the title of the message\",\"message\":\"This is the body of the message\"},\"id\":1}";
  response = webClient.UploadString($"http://{server}:{port}/jsonrpc", "POST", json);
}

如果有人对此有任何见解,将不胜感激。

using HttpClient client = new();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}")))
var json = "{\"jsonrpc\":\"2.0\",\"method\":\"GUI.ShowNotification\",\"params\":{\"title\":\"This is the title of the message\",\"message\":\"This is the body of the message\"},\"id\":1}";
var response = await client.PostAsync($"http://{server}:{port}/jsonrpc", new StringContent(json));