HttpClient Class

Definition

Provides a base 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);
  }
}
' 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.

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

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 channel in one of the constructor overloads taking a HttpMessageHandler instance as parameter. If features like authentication or caching are required, WebRequestHandler can be used to configure settings and the instance can be passed to the constructor. The returned handler can be passed to one of the constructor overloads taking a HttpMessageHandler parameter.

If an app using 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 the default buffering is used the client memory usage will get very large, potentially resulting in substantially reduced performance.

The following methods are thread safe:

  1. CancelPendingRequests

  2. DeleteAsync

  3. GetAsync

  4. GetByteArrayAsync

  5. GetStreamAsync

  6. GetStringAsync

  7. PostAsync

  8. PutAsync

  9. SendAsync

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. Below is an example using HttpClient correctly.

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

    static GoodController()
    {
        HttpClient = new HttpClient();
    }
}
  Public Class GoodController
    Inherits ApiController  
   
    Private Shared ReadOnly HttpClient As HttpClient  
  
    Shared Sub New()  
        HttpClient = New HttpClient()
    End Sub
End Class

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.

HttpClient and .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, you can configure your application to use the older System.Net.Http.HttpClientHandler instead in a number of ways:

  • By calling the AppContext.SetSwitch method as follows:

    AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
    
    AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", False)
    
  • By defining the System.Net.Http.UseSocketsHttpHandler switch in the .netcore.runtimeconfig.json configuration file:

    "runtimeOptions": {
      "configProperties": {
          "System.Net.Http.UseSocketsHttpHandler": false
      }
    }
    
  • By defining an environment variable named DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER and setting it to either false or 0.

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.

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(Uri)

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(Uri)

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(Uri)

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.

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)

Applies to

See also