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 in System.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

FeatureDescription
ClassHttpClient (System.Net.Http)
GET requestGetAsync(url)
POST requestPostAsync(url, HttpContent)
Read responseresponse.Content.ReadAsStringAsync()
Set headersDefaultRequestHeaders.Add()
Best practiceReuse 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.