Using HttpClient with Sync and Async in C#
By FoxLearn 1/9/2025 2:27:13 AM 134
The System.Net.Http.HttpClient() provides a robust HTTP client, but using it can be a challenge, especially if you're not familiar with asynchronous programming like I wasn't.
To help, here's a quick reference guide on how to navigate Task<>, async, and await when working with HttpClient().
I've removed HttpClient
from the using
statement. This change prevents creating a new instance of HttpClient
for each request, which can lead to socket exhaustion.
For example, Using HttpClient
GET with a Return Value
private static readonly HttpClient _httpClient = new HttpClient(); public static async Task<string> GetAsync(string queryString) { string authUserName = "user"; string authPassword = "password"; string url = "https://foxlearn.com"; // Include these lines for basic authentication var authToken = Encoding.ASCII.GetBytes($"{authUserName}:{authPassword}"); _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken)); // The actual GET request using (var response = await _httpClient.GetAsync($"{url}{queryString}")) { string content = await response.Content.ReadAsStringAsync(); return content; } }
Usage:
// Synchronous code: string queryString = "?param=example"; string result = GetAsync(queryString).Result; // Asynchronous code: string queryString = "?param=example"; string result = await GetAsync(queryString);
For example, Using HttpClient
PUT “Fire-and-Forget” Without Return Value
private static readonly HttpClient _httpClient = new HttpClient(); public static async Task PutAsync(string postData) { string authUserName = "user"; string authPassword = "password"; string url = "https://someurl.com"; // Include these lines for basic authentication var authToken = Encoding.ASCII.GetBytes($"{authUserName}:{authPassword}"); _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken)); // The actual PUT request with error handling using (var content = new StringContent(postData)) { var response = await _httpClient.PutAsync(url, content); if (response.StatusCode == HttpStatusCode.OK) { return; } else { // Log the status code and response content string responseContent = await response.Content.ReadAsStringAsync(); // Log the details } } }
Usage:
// Call the method asynchronously and do not wait for the result (fire-and-forget) PutAsync("data"); // If you need to wait for the completion, use .Wait() PutAsync("data").Wait();
This should give you a simple and clear way to work with the HttpClient
class using async
and await
.
- 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
SB Admin Template
11/17/2024
Plus Admin Dashboard Template
11/18/2024
Material Dashboard Admin Template
11/17/2024