Quantcast
Viewing latest article 7
Browse Latest Browse All 275

C# POST x-www-form-urlencoded using HttpClient

To POST x-www-form-urlencoded data in C# using the HttpClient, you can do the following:

using System.Net.Http;
 
private static HttpClient _httpClient = new HttpClient();

public async Task<string> PostFormUrlEncodedData()
{
    var data = new[]
    {
        new KeyValuePair<string, string>("formfield1", "formvalue1"),
        new KeyValuePair<string, string>("formfield2", "formvalue2"),
        new KeyValuePair<string, string>("formfield3", "formvalue3")
    };
    var content = new FormUrlEncodedContent(data);

    var response = await client.PostAsync(url, content);
    if (!response.IsSuccessStatusCode)
        throw new Exception($"{response.StatusCode}: {response.ReasonPhrase}");

    var responseJson = await response.Content.ReadAsStringAsync();
      return responseJson;	
}

The FormUrlEncodedContent will automatically set the content-type to application/x-www-form-urlencoded.

Before using the HttpClient, consider using a HttpClientFactory, as the HttpClient is a shared object and creating a HttpClient for each call will lead to socket exhaustion.

MORE TO READ:


Viewing latest article 7
Browse Latest Browse All 275

Trending Articles