Home > Net >  How to replace obsolete WebClient with HttpClient in .NET 6
How to replace obsolete WebClient with HttpClient in .NET 6

Time:12-03

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

In particular, I have some doubts regarding the setting of Encoding and Headers with HttpClient. Can anyone provide the equivalent code using HttpClient which can replace the above code in .NET 6? Thanks in advance.

CodePudding user response:

Seems simple enough:

HttpClient client = new()
{
    BaseAddress = new Uri(_baseUrl)
};

using HttpRequestMessage request = new(HttpMethod.Post, "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)
{
    Headers =
    {
        ContentType = new("application/json")
    }
};

using HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string serverResponse = await response.Content.ReadAsStringAsync();

However, you'll probably want to use the IHttpClientFactory to create your HttpClient instances, since that provides several benefits - particularly pooling the underlying message handler, to avoid performance problems.

You might also want to consider using the PostAsJsonAsync extension method, which could simplify this code.

CodePudding user response:

Following Richard Deeming's advice, I implemented the following solution:

var httpClient = _httpClientFactory.CreateClient();
httpClient.DefaultRequestHeaders.Add("user_key", tokens[0]);
httpClient.DefaultRequestHeaders.Add("Session_key", tokens[1]);
using var response = await HttpClientJsonExtensions.PostAsJsonAsync(httpClient, _baseUrl   "sms", sms);
response.EnsureSuccessStatusCode();

It seems the most concise and effective way for replacing the original code.

  • Related