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:
- C# Use HttpClient to GET JSON from API endpoint by briancaos
- Is it bad practice to mutate your HttpClient objects? from stackexchange
- C# HttpClient and IHttpClientFactory in .net core by briancaos
- C# HttpClient POST or PUT Json with content type application/json by briancaos
- Using C# HttpClient from Sync and Async code by briancaos