How to Make an HTTP Request with C#
C# uses HttpClient for HTTP requests. It's designed for reuse—create one instance and reuse it across requests.
GET request example
Making a GET request to fetch data with custom headers:
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Authorization", "Bearer YOUR_TOKEN");
var response = await client.GetAsync("https://api.example.com/users");
var content = await response.Content.ReadAsStringAsync();POST request example
Making a POST request to send JSON data:
using var client = new HttpClient();
var json = "{"name":"John","email":"john@example.com"}";
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.example.com/users", content);
var result = await response.Content.ReadAsStringAsync();Other libraries you can try
- Python:
Requests— simple and popular HTTP library,HTTPX— async-capable HTTP client - JavaScript:
Axios— promise-based HTTP client,node-fetch— Fetch API for Node.js - Ruby:
HTTParty— simple HTTP client,Faraday— flexible HTTP library,RestClient— lightweight REST client - Java:
OkHttp— efficient HTTP client,Apache HttpClient— feature-rich library - C#:
RestSharp— simple REST client,Flurl— fluent HTTP library - Go:
resty— simple HTTP client,grequests— goroutine-based requests - PHP:
Guzzle— popular PHP HTTP client,Symfony HttpClient— component-based HTTP client