Letβs go through making HTTP requests in C# using HttpClient
β the standard way to call web APIs or fetch data from the internet.
π 1. What is HttpClient
?
-
HttpClient
is a class inSystem.Net.Http
used for:-
Sending GET, POST, PUT, DELETE requests
-
Communicating with REST APIs
-
Handling HTTP responses asynchronously
-
-
Designed to be reused for multiple requests (avoid creating a new instance per request).
π 2. Creating an HttpClient
Instance
using System.Net.Http;
HttpClient client = new HttpClient();
- For better performance, use a single shared instance:
private static readonly HttpClient client = new HttpClient();
π 3. Making a GET Request
using System;
using System.Net.Http;
using System.Threading.Tasks;
async Task GetExample()
{
string url = "https://jsonplaceholder.typicode.com/todos/1";
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
-
GetAsync()
β sends a GET request -
ReadAsStringAsync()
β reads response body
π 4. Making a POST Request
using System.Net.Http;
using System.Text;
using System.Text.Json;
var data = new { title = "New Task", completed = false };
string json = JsonSerializer.Serialize(data);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/todos", content);
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
-
StringContent
wraps the JSON payload -
Specify encoding and media type (
application/json
)
π 5. Handling Other HTTP Methods
await client.PutAsync(url, content); // Update resource
await client.DeleteAsync(url); // Delete resource
await client.PatchAsync(url, content); // Partial update (needs extension method or custom HttpMethod)
- Supports all standard HTTP verbs
π 6. Setting Headers
client.DefaultRequestHeaders.Add("Authorization", "Bearer your_token_here");
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")
);
- Useful for authentication, API keys, or content negotiation
π 7. Disposing HttpClient
-
Avoid frequent creation/disposal to prevent socket exhaustion
-
Prefer long-lived instances or use
IHttpClientFactory
in ASP.NET Core
π 8. Summary Table
Feature | Description |
---|---|
Class | HttpClient (System.Net.Http) |
GET request | GetAsync(url) |
POST request | PostAsync(url, HttpContent) |
Read response | response.Content.ReadAsStringAsync() |
Set headers | DefaultRequestHeaders.Add() |
Best practice | Reuse HttpClient instance, use async/await |
β Tip:
-
Always use async methods (
GetAsync
,PostAsync
) to keep your app responsive. -
For ASP.NET Core apps, consider IHttpClientFactory to manage HttpClient lifetimes efficiently.