How to Send x-www-form-urlencoded Data with HttpClient in C#
By FoxLearn 1/9/2025 2:01:52 AM 56
To send x-www-form-urlencoded data in C# using HttpClient, you can follow these steps:
using System.Net.Http; using System.Collections.Generic; using System.Threading.Tasks; public class MyHttpService { private readonly HttpClient _httpClient; // Injecting IHttpClientFactory into the constructor public MyHttpService(IHttpClientFactory httpClientFactory) { _httpClient = httpClientFactory.CreateClient(); } public async Task<string> PostFormUrlEncodedData(string url) { 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); // Perform the POST request var response = await _httpClient.PostAsync(url, content); // Check for success status code if (!response.IsSuccessStatusCode) { throw new Exception($"{response.StatusCode}: {response.ReasonPhrase}"); } // Read and return the response content as string var responseJson = await response.Content.ReadAsStringAsync(); return responseJson; } }
The FormUrlEncodedContent
automatically assigns the Content-Type
header to application/x-www-form-urlencoded
.
Using IHttpClientFactory
ensures that HttpClient
instances are reused and not created for each request, which is a best practice for managing HTTP connections.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Plus Admin Dashboard Template
11/18/2024
Dash UI HTML5 Admin Dashboard Template
11/18/2024
Material Dashboard Admin Template
11/17/2024