HttpClient
Summary
A HttpClient class represents an abstraction over HTTP.
It's a modern and recommended way to make HTTP requests in .NET applications,
offering better performance, flexibility, and control compared to older methods.
It supports asynchronous operations for non-blocking network calls.
Remarks
It is recommended that you instantiate a single HttpClient
object and reuse it throughout the life of an application.
Creating an HttpClient object is also relatively expensive and
reusing an instance will benefit performance.
See the remarks for HttpClient.Create for more details.
The HttpClient class supports the following features:
- Asynchronous operations (
async/await) for non-blocking requests. - Request and response message encapsulation via
HttpRequestMessageandHttpResponseMessage. - Customizable request headers and content.
- Support for various HTTP methods (GET, POST, PUT, DELETE, etc.).
- Connection pooling and management for efficiency.
- Cancellation tokens for aborting ongoing requests.
Constructors
-
public HttpClient()Initializes a new instance of the
HttpClientclass. -
public HttpClient(HttpMessageHandler handler)Initializes a new instance of the
HttpClientclass with a specificHttpMessageHandler. -
public HttpClient(HttpMessageHandler handler, bool disposeHandler)Initializes a new instance of the
HttpClientclass with a specificHttpMessageHandlerand a value indicating whether the handler should be disposed.
Methods
-
public Task
GetAsync(string requestUri) Send a GET request to the specified Uri as an asynchronous operation.ParametersReturnsExampleParameters
string requestUri: The Uri to request; this can be an absolute or relative Uri.
Returns
The task object representing the asynchronous operation.
The
Resultproperty of the task object contains aHttpResponseMessagedescribing the response to the request.Example
using System; using System.Net.Http; using System.Threading.Tasks; public class Example { public static async Task Main(string[] args) { using (HttpClient client = new HttpClient()) { try { HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1"); response.EnsureSuccessStatusCode(); // Throw if HTTP status is 4xx or 5xx string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"\nException Caught!"); Console.WriteLine($"Message :{e.Message} "); } } } } -
public Task
PostAsync(string requestUri, HttpContent content) Send a POST request to the specified Uri as an asynchronous operation.ParametersReturnsParameters
string requestUri: The Uri to send the POST request to.HttpContent content: The HTTP content to send with the request.
Returns
The task object representing the asynchronous operation. The
Resultproperty of the task object contains aHttpResponseMessage. -
public async Task
GetStringAsync(string requestUri) Send a GET request to the specified Uri and return the response body as a string as an asynchronous operation.ParametersReturnsParameters
string requestUri: The Uri to request.
Returns
The task object representing the asynchronous operation. The
Resultproperty of the task object contains the response body as a string. -
public void Dispose()Releases the unmanaged resources that are used by the current instance of the
HttpClientclass and optionally releases the managed resources.
Properties
-
public HttpCompletionOption CompletionOption { get; set; }Gets or sets the way to complete an asynchronous operation.
-
public HttpHeaders DefaultRequestHeaders { get; }Gets or sets the HTTP headers sent with every request.
-
public Uri BaseAddress { get; set; }Gets or sets the base address of Uniform Resource Identifiers (URIs) for requests made by this instance.