How to Send x-www-form-urlencoded Data with HttpClient in C#
By FoxLearn 2/7/2025 7:11:44 AM 392
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.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024