Sending HTTP requests to some external endpoints using C# is something I have to do quite often in my projects. We have numerous libraries like RestSharp for this purpose.
In this post, we'll learn to use the Ā HttpClient class from System.Net.Http to send HTTP requests from C# applications with x-www-form-urlencoded data.
Sending Post Request
To send a post request, we should, first, create an object of the HttpClient class and use its PostAsync() method to send the actual post request.
string endPoint = "https://hookb.in/QJ0QKKD7yzt8mNzzmz2J";
var client = new HttpClient();
In order to send the data in x-www-form-urlencoded format, we can use FormUrlEncodedContent class. It accepts the data as an IEnumerable of KeyValue pairs.
var data = new[]
{
new KeyValuePair<string, string>("name", "John Doe"),
new KeyValuePair<string, string>("email", "johndoe@example.com"),
};
Next, we can send the actual post request using the PostAsync method.
await client.PostAsync(endPoint, new FormUrlEncodedContent(data));
If you are not calling this method from an async method, user GetAwaiter().GetResult().
client.PostAsync(endPoint, new FormUrlEncodedContent(data)).GetAwaiter().GetResult();
Here's the complete code.
public static void Main()
{
string endPoint = "https://hookb.in/QJ0QKKD7yzt8mNzzmz2J";
var client = new HttpClient();
var data = new[]
{
new KeyValuePair<string, string>("name", "John Doe"),
new KeyValuePair<string, string>("email", "johndoe@example.com"),
};
client.PostAsync(endPoint, new FormUrlEncodedContent(data)).GetAwaiter().GetResult();
}
Check this link to see the request sent from our application.
Happy coding š.