Home > Software engineering >  Migrate WebClient JSON-RPC calls to HttpClient in C#
Migrate WebClient JSON-RPC calls to HttpClient in C#

Time:04-10

I would like to accomplish the same thing as this using HttpClient in .Net 6

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);
}

If anyone has any insight on this it would be greatly appreciated.

CodePudding user response:

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));
  • Related