HttpClient Class

System.Net.Http

Summary

Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified over a network.

The HttpClient class is an IDisposable object. It is recommended that you use a single instance of HttpClient for the lifetime of an application. For more information, see HttpClient lifecycle management.

The HttpClient class implements the modern, more performant way of making HTTP requests. It supports asynchronous operations and is designed for extensibility.

Syntax

public sealed class HttpClient : IDisposable

Constructors

Name Description
HttpClient() Initializes a new instance of the HttpClient class with the default configuration.
HttpClient(HttpMessageHandler) Initializes a new instance of the HttpClient class with a custom handler.
HttpClient(HttpMessageHandler, Boolean) Initializes a new instance of the HttpClient class with a custom handler and a value that indicates whether the handler's Dispose method should be called.

Methods

Name Description
DeleteAsync(String) Send an HTTP DELETE request to the specified URI as an asynchronous operation.
GetAsync(String) Send an HTTP GET request to the specified URI as an asynchronous operation.
PostAsync(String, HttpContent) Send an HTTP POST request to the specified URI as an asynchronous operation.
PutAsync(String, HttpContent) Send an HTTP PUT request to the specified URI as an asynchronous operation.
SendAsync(HttpRequestMessage) Send an HTTP request as an asynchronous operation.
Dispose() Releases the unmanaged resources that are used by the HttpClient and optionally releases the managed resources.

Properties

Name Description
DefaultRequestHeaders Gets or sets the default request headers to send with requests on this HttpClient.
Timeout Gets or sets the time to wait for the server to send the response to the request.

Example

The following code example demonstrates how to use the HttpClient class to send a GET request and display the response content.

using System; using System.Net.Http; using System.Threading.Tasks; public class Example { public static async Task Main(string[] args) { // Use a single HttpClient instance for the lifetime of the application using (var client = new HttpClient()) { try { // Send a GET request to a sample API HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1"); // Ensure the request was successful response.EnsureSuccessStatusCode(); // Read the response content as a string string responseBody = await response.Content.ReadAsStringAsync(); // Print the response body Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine("\nException Caught!"); Console.WriteLine("Message :" + e.Message); } } } }

Assembly: System.Net.Http.dll

Namespace: System.Net.Http

Last Updated: 2023-10-27