How to Send x-www-form-urlencoded Data with HttpClient in C#
By Tan Lee Published on Jan 09, 2025 743
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.
Categories
Popular Posts
Freedash bootstrap lite
Nov 13, 2024
Material Lite Admin Template
Nov 14, 2024
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Material Dashboard Admin Template
Nov 17, 2024