HttpClient Class

Definition

Provides a class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

public ref class HttpClient : System::Net::Http::HttpMessageInvoker
public class HttpClient : System.Net.Http.HttpMessageInvoker
type HttpClient = class
    inherit HttpMessageInvoker
Public Class HttpClient
Inherits HttpMessageInvoker
Inheritance

Examples

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();

static async Task Main()
{
  // Call asynchronous network methods in a try/catch block to handle exceptions.
  try	
  {
     HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // Above three lines can be replaced with new helper method below
     // string responseBody = await client.GetStringAsync(uri);

     Console.WriteLine(responseBody);
  }
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");	
     Console.WriteLine("Message :{0} ",e.Message);
  }
}
open System.Net.Http

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
let client = new HttpClient()

let main =
    task {
        // Call asynchronous network methods in a try/catch block to handle exceptions.
        try
            let! response = client.GetAsync "http://www.contoso.com/"
            response.EnsureSuccessStatusCode() |> ignore
            let! responseBody = response.Content.ReadAsStringAsync()
            // Above three lines can be replaced with new helper method below
            // let! responseBody = client.GetStringAsync uri

            printfn $"{responseBody}"
        with
        | :? HttpRequestException as e ->
            printfn "\nException Caught!"
            printfn $"Message :{e.Message} "
    }

main.Wait()
' HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
Shared ReadOnly client As HttpClient = New HttpClient()

Private Shared Async Function Main() As Task
    ' Call asynchronous network methods in a try/catch block to handle exceptions.
    Try
        Dim response As HttpResponseMessage = Await client.GetAsync("http://www.contoso.com/")
        response.EnsureSuccessStatusCode()
        Dim responseBody As String = Await response.Content.ReadAsStringAsync()
        ' Above three lines can be replaced with new helper method below
        ' Dim responseBody As String = Await client.GetStringAsync(uri)

        Console.WriteLine(responseBody)
    Catch e As HttpRequestException
        Console.WriteLine(Environment.NewLine & "Exception Caught!")
        Console.WriteLine("Message :{0} ", e.Message)
    End Try
End Function

The preceding code example uses an async Task Main() entry point. That feature requires C# 7.1 or later.

Remarks

The HttpClient class instance acts as a session to send HTTP requests. An HttpClient instance is a collection of settings applied to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool, isolating its requests from requests executed by other HttpClient instances.

Instancing

HttpClient is intended to be instantiated once and reused throughout the life of an application. In .NET Core and .NET 5+, HttpClient pools connections inside the handler instance and reuses a connection across multiple requests. If you instantiate an HttpClient class for every request, the number of sockets available under heavy loads will be exhausted. This exhaustion will result in SocketException errors.

You can configure additional options by passing in a "handler", such as HttpClientHandler (or SocketsHttpHandler in .NET Core 2.1 or later), as part of the constructor. The connection properties on the handler cannot be changed once a request has been submitted, so one reason to create a new HttpClient instance would be if you need to change the connection properties. If different requests require different settings, this may also lead to an application having multiple HttpClient instances, where each instance is configured appropriately, and then requests are issued on the relevant client.

HttpClient only resolves DNS entries when a connection is created. It does not track any time to live (TTL) durations specified by the DNS server. If DNS entries change regularly, which can happen in some container scenarios, the client won't respect those updates. To solve this issue, you can limit the lifetime of the connection by setting the SocketsHttpHandler.PooledConnectionLifetime property, so that DNS lookup is required when the connection is replaced.

public class GoodController : ApiController
{
    private static readonly HttpClient httpClient;

    static GoodController()
    {
        var socketsHandler = new SocketsHttpHandler
        {
            PooledConnectionLifetime = TimeSpan.FromMinutes(2)
        };

        httpClient = new HttpClient(socketsHandler);
    }
}

As an alternative to creating only one HttpClient instance, you can also use IHttpClientFactory to manage the HttpClient instances for you. For more information, see Guidelines for using HttpClient.

Derivation

The HttpClient also acts as a base class for more specific HTTP clients. An example would be a FacebookHttpClient that provides additional methods specific to a Facebook web service (for example, a GetFriends method). Derived classes should not override the virtual methods on the class. Instead, use a constructor overload that accepts HttpMessageHandler to configure any pre-request or post-request processing.

Transports

The HttpClient is a high-level API that wraps the lower-level functionality available on each platform where it runs.

On each platform, HttpClient tries to use the best available transport:

Host/Runtime Backend
Windows/.NET Framework HttpWebRequest
Windows/Mono HttpWebRequest
Windows/UWP Windows native WinHttpHandler (HTTP 2.0 capable)
Windows/.NET Core 1.0-2.0 Windows native WinHttpHandler (HTTP 2.0 capable)
Android/Xamarin Selected at build-time. Can either use HttpWebRequest or be configured to use Android's native HttpURLConnection
iOS, tvOS, watchOS/Xamarin Selected at build-time. Can either use HttpWebRequest or be configured to use Apple's NSUrlSession (HTTP 2.0 capable)
macOS/Xamarin Selected at build-time. Can either use HttpWebRequest or be configured to use Apple's NSUrlSession (HTTP 2.0 capable)
macOS/Mono HttpWebRequest
macOS/.NET Core 1.0-2.0 libcurl-based HTTP transport (HTTP 2.0 capable)
Linux/Mono HttpWebRequest
Linux/.NET Core 1.0-2.0 libcurl-based HTTP transport (HTTP 2.0 capable)
.NET Core 2.1 and later System.Net.Http.SocketsHttpHandler

Users can also configure a specific transport for HttpClient by invoking the HttpClient constructor that takes an HttpMessageHandler.

.NET Framework & Mono

By default on .NET Framework and Mono, HttpWebRequest is used to send requests to the server. This behavior can be modified by specifying a different handler in one of the constructor overloads with an HttpMessageHandler parameter. If you require features like authentication or caching, you can use WebRequestHandler to configure settings and the instance can be passed to the constructor. The returned handler can be passed to a constructor overload that has an HttpMessageHandler parameter.

.NET Core

Starting with .NET Core 2.1, the System.Net.Http.SocketsHttpHandler class instead of HttpClientHandler provides the implementation used by higher-level HTTP networking classes such as HttpClient. The use of SocketsHttpHandler offers a number of advantages:

  • A significant performance improvement when compared with the previous implementation.
  • The elimination of platform dependencies, which simplifies deployment and servicing. For example, libcurl is no longer a dependency on .NET Core for macOS and .NET Core for Linux.
  • Consistent behavior across all .NET platforms.

If this change is undesirable, on Windows you can continue to use WinHttpHandler by referencing its NuGet package and passing it to HttpClient's constructor manually.

Configure behavior using runtime configuration options

Certain aspects of HttpClient's behavior are customizable through Runtime configuration options. However, the behavior of these switches differs through .NET versions. For example, in .NET Core 2.1 - 3.1, you can configure whether SocketsHttpHandler is used by default, but that option is no longer available starting in .NET 5.0.

Connection pooling

HttpClient pools HTTP connections where possible and uses them for more than one request. This can have a significant performance benefit, especially for HTTPS requests, as the connection handshake is only done once.

Connection pool properties can be configured on a HttpClientHandler or SocketsHttpHandler passed in during construction, including MaxConnectionsPerServer, PooledConnectionIdleTimeout, and PooledConnectionLifetime.

Disposing of the HttpClient instance closes the open connections and cancels any pending requests.

Note

If you concurrently send HTTP/1.1 requests to the same server, new connections can be created. Even if you reuse the HttpClient instance, if the rate of requests is high, or if there are any firewall limitations, that can exhaust the available sockets because of default TCP cleanup timers. To limit the number of concurrent connections, you can set the MaxConnectionsPerServer property. By default, the number of concurrent HTTP/1.1 connections is unlimited.

Buffering and request lifetime

By default, HttpClient methods (except GetStreamAsync) buffer the responses from the server, reading all the response body into memory before returning the async result. Those requests will continue until one of the following occurs:

You can change the buffering behavior on a per-request basis using the HttpCompletionOption parameter available on some method overloads. This argument can be used to specify if the Task<TResult> should be considered complete after reading just the response headers, or after reading and buffering the response content.

If your app that uses HttpClient and related classes in the System.Net.Http namespace intends to download large amounts of data (50 megabytes or more), then the app should stream those downloads and not use the default buffering. If you use the default buffering, the client memory usage will get very large, potentially resulting in substantially reduced performance.

Thread safety

The following methods are thread safe:

Proxies

By default, HttpClient reads proxy configuration from environment variables or user/system settings, depending on the platform. You can change this behavior by passing a WebProxy or IWebProxy to, in order of precedence:

  • The Proxy property on a HttpClientHandler passed in during HttpClient construction
  • The DefaultProxy static property (affects all instances)

You can disable the proxy using UseProxy. The default configuration for Windows users is to try and detect a proxy using network discovery, which can be slow. For high throughput applications where it's known that a proxy isn't required, you should disable the proxy.

Timeouts

You can use Timeout to set a default timeout for all HTTP requests from the HttpClient instance. The timeout only applies to the xxxAsync methods that cause a request/response to be initiated. If the timeout is reached, the Task<TResult> for that request is cancelled.

You can set some additional timeouts if you pass in a SocketsHttpHandler instance when constructing the HttpClient object:

Property Description
ConnectTimeout Specifies a timeout that's used when a request requires a new TCP connection to be created. If the timeout occurs, the request Task<TResult> is cancelled.
PooledConnectionLifetime Specifies a timeout to be used for each connection in the connection pool. If the connection is idle, the connection is immediately closed; otherwise, the connection is closed at the end of the current request.
PooledConnectionIdleTimeout If a connection in the connection pool is idle for this long, the connection is closed.
Expect100ContinueTimeout If request has an "Expect: 100-continue" header, it delays sending content until the timeout or until a "100-continue" response is received.

HttpClient only resolves DNS entries when the connections are created. It does not track any time to live (TTL) durations specified by the DNS server. If DNS entries are changing regularly, which can happen in some container scenarios, you can use the PooledConnectionLifetime to limit the lifetime of the connection so that DNS lookup is required when replacing the connection.

Constructors

HttpClient()

Initializes a new instance of the HttpClient class using a HttpClientHandler that is disposed when this instance is disposed.

HttpClient(HttpMessageHandler)

Initializes a new instance of the HttpClient class with the specified handler. The handler is disposed when this instance is disposed.

HttpClient(HttpMessageHandler, Boolean)

Initializes a new instance of the HttpClient class with the provided handler, and specifies whether that handler should be disposed when this instance is disposed.

Properties

BaseAddress

Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.

DefaultProxy

Gets or sets the global Http proxy.

DefaultRequestHeaders

Gets the headers which should be sent with each request.

DefaultRequestVersion

Gets or sets the default HTTP version used on subsequent requests made by this HttpClient instance.

DefaultVersionPolicy

Gets or sets the default version policy for implicitly created requests in convenience methods, for example, GetAsync(String) and PostAsync(String, HttpContent).

MaxResponseContentBufferSize

Gets or sets the maximum number of bytes to buffer when reading the response content.

Timeout

Gets or sets the timespan to wait before the request times out.

Methods

CancelPendingRequests()

Cancel all pending requests on this instance.

DeleteAsync(String)

Send a DELETE request to the specified Uri as an asynchronous operation.

DeleteAsync(String, CancellationToken)

Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.

DeleteAsync(Uri)

Send a DELETE request to the specified Uri as an asynchronous operation.

DeleteAsync(Uri, CancellationToken)

Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.

Dispose()

Releases the unmanaged resources and disposes of the managed resources used by the HttpMessageInvoker.

(Inherited from HttpMessageInvoker)
Dispose(Boolean)

Releases the unmanaged resources used by the HttpClient and optionally disposes of the managed resources.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetAsync(String)

Send a GET request to the specified Uri as an asynchronous operation.

GetAsync(String, CancellationToken)

Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.

GetAsync(String, HttpCompletionOption)

Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation.

GetAsync(String, HttpCompletionOption, CancellationToken)

Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation.

GetAsync(Uri)

Send a GET request to the specified Uri as an asynchronous operation.

GetAsync(Uri, CancellationToken)

Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.

GetAsync(Uri, HttpCompletionOption)

Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation.

GetAsync(Uri, HttpCompletionOption, CancellationToken)

Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation.

GetByteArrayAsync(String)

Sends a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.

GetByteArrayAsync(String, CancellationToken)

Sends a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.

GetByteArrayAsync(Uri)

Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.

GetByteArrayAsync(Uri, CancellationToken)

Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetStreamAsync(String)

Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.

GetStreamAsync(String, CancellationToken)

Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.

GetStreamAsync(Uri)

Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.

GetStreamAsync(Uri, CancellationToken)

Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.

GetStringAsync(String)

Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.

GetStringAsync(String, CancellationToken)

Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.

GetStringAsync(Uri)

Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.

GetStringAsync(Uri, CancellationToken)

Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.

GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
PatchAsync(String, HttpContent)

Sends a PATCH request to a Uri designated as a string as an asynchronous operation.

PatchAsync(String, HttpContent, CancellationToken)

Sends a PATCH request with a cancellation token to a Uri represented as a string as an asynchronous operation.

PatchAsync(Uri, HttpContent)

Sends a PATCH request as an asynchronous operation.

PatchAsync(Uri, HttpContent, CancellationToken)

Sends a PATCH request with a cancellation token as an asynchronous operation.

PostAsync(String, HttpContent)

Send a POST request to the specified Uri as an asynchronous operation.

PostAsync(String, HttpContent, CancellationToken)

Send a POST request with a cancellation token as an asynchronous operation.

PostAsync(Uri, HttpContent)

Send a POST request to the specified Uri as an asynchronous operation.

PostAsync(Uri, HttpContent, CancellationToken)

Send a POST request with a cancellation token as an asynchronous operation.

PutAsync(String, HttpContent)

Send a PUT request to the specified Uri as an asynchronous operation.

PutAsync(String, HttpContent, CancellationToken)

Send a PUT request with a cancellation token as an asynchronous operation.

PutAsync(Uri, HttpContent)

Send a PUT request to the specified Uri as an asynchronous operation.

PutAsync(Uri, HttpContent, CancellationToken)

Send a PUT request with a cancellation token as an asynchronous operation.

Send(HttpRequestMessage)

Sends an HTTP request with the specified request.

Send(HttpRequestMessage, CancellationToken)

Sends an HTTP request with the specified request and cancellation token.

Send(HttpRequestMessage, CancellationToken)

Sends an HTTP request with the specified request and cancellation token.

(Inherited from HttpMessageInvoker)
Send(HttpRequestMessage, HttpCompletionOption)

Sends an HTTP request.

Send(HttpRequestMessage, HttpCompletionOption, CancellationToken)

Sends an HTTP request with the specified request, completion option and cancellation token.

SendAsync(HttpRequestMessage)

Send an HTTP request as an asynchronous operation.

SendAsync(HttpRequestMessage, CancellationToken)

Send an HTTP request as an asynchronous operation.

SendAsync(HttpRequestMessage, HttpCompletionOption)

Send an HTTP request as an asynchronous operation.

SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken)

Send an HTTP request as an asynchronous operation.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Extension Methods

GetFromJsonAsync(HttpClient, String, Type, JsonSerializerOptions, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync(HttpClient, String, Type, JsonSerializerContext, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync(HttpClient, String, Type, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync(HttpClient, Uri, Type, JsonSerializerOptions, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync(HttpClient, Uri, Type, JsonSerializerContext, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync(HttpClient, Uri, Type, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync<TValue>(HttpClient, String, JsonSerializerOptions, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync<TValue>(HttpClient, String, JsonTypeInfo<TValue>, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync<TValue>(HttpClient, String, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync<TValue>(HttpClient, Uri, JsonSerializerOptions, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync<TValue>(HttpClient, Uri, JsonTypeInfo<TValue>, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

GetFromJsonAsync<TValue>(HttpClient, Uri, CancellationToken)

Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

PatchAsJsonAsync<TValue>(HttpClient, String, TValue, JsonSerializerOptions, CancellationToken)

Sends a PATCH request to the specified Uri containing the value serialized as JSON in the request body.

PatchAsJsonAsync<TValue>(HttpClient, String, TValue, JsonTypeInfo<TValue>, CancellationToken)

Sends a PATCH request to the specified Uri containing the value serialized as JSON in the request body.

PatchAsJsonAsync<TValue>(HttpClient, String, TValue, CancellationToken)

Sends a PATCH request to the specified Uri containing the value serialized as JSON in the request body.

PatchAsJsonAsync<TValue>(HttpClient, Uri, TValue, JsonSerializerOptions, CancellationToken)

Sends a PATCH request to the specified Uri containing the value serialized as JSON in the request body.

PatchAsJsonAsync<TValue>(HttpClient, Uri, TValue, JsonTypeInfo<TValue>, CancellationToken)

Sends a PATCH request to the specified Uri containing the value serialized as JSON in the request body.

PatchAsJsonAsync<TValue>(HttpClient, Uri, TValue, CancellationToken)

Sends a PATCH request to the specified Uri containing the value serialized as JSON in the request body.

PostAsJsonAsync<TValue>(HttpClient, String, TValue, JsonSerializerOptions, CancellationToken)

Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.

PostAsJsonAsync<TValue>(HttpClient, String, TValue, JsonTypeInfo<TValue>, CancellationToken)

Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.

PostAsJsonAsync<TValue>(HttpClient, String, TValue, CancellationToken)

Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.

PostAsJsonAsync<TValue>(HttpClient, Uri, TValue, JsonSerializerOptions, CancellationToken)

Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.

PostAsJsonAsync<TValue>(HttpClient, Uri, TValue, JsonTypeInfo<TValue>, CancellationToken)

Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.

PostAsJsonAsync<TValue>(HttpClient, Uri, TValue, CancellationToken)

Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.

PutAsJsonAsync<TValue>(HttpClient, String, TValue, JsonSerializerOptions, CancellationToken)

Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.

PutAsJsonAsync<TValue>(HttpClient, String, TValue, JsonTypeInfo<TValue>, CancellationToken)

Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.

PutAsJsonAsync<TValue>(HttpClient, String, TValue, CancellationToken)

Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.

PutAsJsonAsync<TValue>(HttpClient, Uri, TValue, JsonSerializerOptions, CancellationToken)

Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.

PutAsJsonAsync<TValue>(HttpClient, Uri, TValue, JsonTypeInfo<TValue>, CancellationToken)

Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.

PutAsJsonAsync<TValue>(HttpClient, Uri, TValue, CancellationToken)

Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.

Applies to

See also