How to Send x-www-form-urlencoded Data with HttpClient in C#
By FoxLearn 2/7/2025 7:11:44 AM 222
To post x-www-form-urlencoded data in C# using HttpClient, you can follow these steps:
For example, c# post x-www-form-urlencoded using HttpClient
using System; using System.Net.Http; using System.Collections.Generic; using System.Threading.Tasks; public class ApiClient { private static HttpClient _httpClient = new HttpClient(); public async Task<string> PostLoginFormData() { // Prepare form data var data = new[] { new KeyValuePair<string, string>("username", "user123"), new KeyValuePair<string, string>("password", "password123"), new KeyValuePair<string, string>("rememberMe", "true") }; // Set up the content with x-www-form-urlencoded var content = new FormUrlEncodedContent(data); // Send the POST request to the server (replace with your API URL) var response = await _httpClient.PostAsync("https://example.com/login", content); // Check for errors in the response if (!response.IsSuccessStatusCode) { throw new Exception($"{response.StatusCode}: {response.ReasonPhrase}"); } // Read and return the response content (assumed to be JSON) var responseJson = await response.Content.ReadAsStringAsync(); return responseJson; } }
In this example:
- Form Data: A
KeyValuePair<string, string>
array holds the form fields ("username"
,"password"
,"rememberMe"
). - FormUrlEncodedContent: This is automatically encoded to
application/x-www-form-urlencoded
. - PostAsync: Sends a POST request with the form data as the content.
- Error Handling: If the response is unsuccessful, it throws an exception with the status code and reason phrase.
- Response: Reads the response body (assumed to be JSON in this case)
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#