To use HttpClient
in C# to send form URL-encoded data, you need to perform the following steps:
- Create an instance of
HttpClient
. - Create an instance of
HttpContent
, specificallyFormUrlEncodedContent
to hold your form data. - Set up your form data as key-value pairs.
- Send the form data using the
PostAsync
method ofHttpClient
.
Here is a step-by-step example:
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Base address is optional but helps in managing relative URIs
var baseAddress = new Uri("http://yourapi.com/");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
// Form data is typically sent as key-value pairs
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("key1", "value1"),
new KeyValuePair<string, string>("key2", "value2")
};
// Encodes the key-value pairs for the ContentType 'application/x-www-form-urlencoded'
HttpContent content = new FormUrlEncodedContent(formData);
try
{
// Send a POST request to the specified Uri as an asynchronous operation.
HttpResponseMessage response = await httpClient.PostAsync("api/endpoint", content);
// Ensure we get a successful response.
response.EnsureSuccessStatusCode();
// Read the response as a string.
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
catch (HttpRequestException e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
}
In this example:
baseAddress
is the base URI of the API or website you are sending requests to.httpClient
is the instance ofHttpClient
that will be used to send the request.formData
is a list of key-value pairs that represent the form data you want to send.FormUrlEncodedContent
is used to encode the form data and set theContent-Type
header toapplication/x-www-form-urlencoded
.PostAsync
sends a POST request to the specified endpoint with the encoded form data.EnsureSuccessStatusCode
will throw an exception if the HTTP response status code does not indicate success.ReadAsStringAsync
reads the response body as a string.
Remember, when using HttpClient
, it's recommended to create a single instance and reuse it throughout the life of an application, instead of creating a new instance for every request. This helps to reduce the number of sockets in TIME_WAIT state and improve the performance of your application.
Additionally, always ensure to handle exceptions that may occur during the request, such as HttpRequestException
, and possibly others depending on the context of your use case.