Since WebClient is deprecated in .NET 6, I want to convert the following code using WebClient with an equivalent code using HttpClient for calling a REST Web API:
using WebClient client = new();
client.Encoding = Encoding.UTF8;
client.Headers.Set(HttpRequestHeader.ContentType, "application/json");
client.Headers.Add("user_key", tokens[0]);
client.Headers.Add("Session_key", tokens[1]);
string json = JsonSerializer.Serialize(sms);
string serverResponse = client.UploadString(_baseUrl + "sms", "POST", json);
For now, I implemented the following solution:
HttpClient httpClient = _httpClientFactory.CreateClient();
HttpRequestMessage request = new(HttpMethod.Post, _baseUrl + "sms");
request.Headers.Add("user_key", tokens[0]);
request.Headers.Add("Session_key", tokens[1]);
string json = JsonSerializer.Serialize(sms);
request.Content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);
using HttpResponseMessage response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
I think that the above solution is the cleanest and most efficient way to replace the original code. Can an EXPERT confirm this?