- HttpClient
- Overview of HttpClient and the Windows.Web.Http namespace
- Send a simple GET request over HTTP
- POST binary data over HTTP
- POST JSON data over HTTP
- Exceptions in Windows.Web.Http
- Http Client Class
- Definition
- Examples
- Remarks
- HttpClient and .NET Core
- Configure behavior using run-time configuration options
- Constructors
- Properties
- Methods
- Extension Methods
HttpClient
Important APIs
Use HttpClient and the rest of the Windows.Web.Http namespace API to send and receive information using the HTTP 2.0 and HTTP 1.1 protocols.
Overview of HttpClient and the Windows.Web.Http namespace
The classes in the Windows.Web.Http namespace and the related Windows.Web.Http.Headers and Windows.Web.Http.Filters namespaces provide a programming interface for Universal Windows Platform (UWP) apps that act as an HTTP client to perform basic GET requests or implement more advanced HTTP functionality listed below.
Methods for common verbs (DELETE, GET, PUT, and POST). Each of these requests are sent as an asynchronous operation.
Support for common authentication settings and patterns.
Access to Secure Sockets Layer (SSL) details on the transport.
Ability to include customized filters in advanced apps.
Ability to get, set, and delete cookies.
HTTP Request progress info available on asynchronous methods.
The Windows.Web.Http.HttpRequestMessage class represents an HTTP request message sent by Windows.Web.Http.HttpClient. The Windows.Web.Http.HttpResponseMessage class represents an HTTP response message received from an HTTP request. HTTP messages are defined in RFC 2616 by the IETF.
The Windows.Web.Http namespace represents HTTP content as the HTTP entity body and headers including cookies. HTTP content can be associated with an HTTP request or an HTTP response. The Windows.Web.Http namespace provides a number of different classes to represent HTTP content.
- HttpBufferContent. Content as a buffer
- HttpFormUrlEncodedContent. Content as name and value tuples encoded with the application/x-www-form-urlencoded MIME type
- HttpMultipartContent. Content in the form of the multipart/* MIME type.
- HttpMultipartFormDataContent. Content that is encoded as the multipart/form-data MIME type.
- HttpStreamContent. Content as a stream (the internal type is used by the HTTP GET method to receive data and the HTTP POST method to upload data)
- HttpStringContent. Content as a string.
- IHttpContent — A base interface for developers to create their own content objects
The code snippet in the «Send a simple GET request over HTTP» section uses the HttpStringContent class to represent the HTTP response from an HTTP GET request as a string.
The Windows.Web.Http.Headers namespace supports creation of HTTP headers and cookies, which are then associated as properties with HttpRequestMessage and HttpResponseMessage objects.
Send a simple GET request over HTTP
As mentioned earlier in this article, the Windows.Web.Http namespace allows UWP apps to send GET requests. The following code snippet demonstrates how to send a GET request to http://www.contoso.com using the Windows.Web.Http.HttpClient class and the Windows.Web.Http.HttpResponseMessage class to read the response from the GET request.
POST binary data over HTTP
The C++/WinRT code example below illustrates using form data and a POST request to send a small amount of binary data as a file upload to a web server. The code uses the HttpBufferContent class to represent the binary data, and the HttpMultipartFormDataContent class to represent the multi-part form data.
Calling get (as seen in the code example below) isn’t appropriate for a UI thread. For the correct technique to use in that case, see Concurrency and asynchronous operations with C++/WinRT.
To POST the contents of an actual binary file (rather than the explicit binary data used above), you’ll find it easier to use an HttpStreamContent object. Construct one and, as the argument to its constructor, pass the value returned from a call to StorageFile.OpenReadAsync. That method returns a stream for the data inside your binary file.
Also, if you’re uploading a large file (larger than about 10MB), then we recommend that you use the Windows Runtime Background Transfer APIs.
POST JSON data over HTTP
The following example posts some JSON to an endpoint, then writes out the response body.
Exceptions in Windows.Web.Http
An exception is thrown when an invalid string for a the Uniform Resource Identifier (URI) is passed to the constructor for the Windows.Foundation.Uri object.
In C# and Visual Basic, this error can be avoided by using the System.Uri class in the .NET 4.5 and one of the System.Uri.TryCreate methods to test the string received from a user before the URI is constructed.
In C++, there is no method to try and parse a string to a URI. If an app gets input from the user for the Windows.Foundation.Uri, the constructor should be in a try/catch block. If an exception is thrown, the app can notify the user and request a new hostname.
The Windows.Web.Http lacks a convenience function. So an app using HttpClient and other classes in this namespace needs to use the HRESULT value.
In apps using C++/WinRT, the winrt::hresult_error struct represents an exception raised during app execution. The winrt::hresult_error::code function returns the HRESULT assigned to the specific exception. The winrt::hresult_error::message function returns the system-provided string that is associated with the HRESULT value. For more info, see Error handling with C++/WinRT
Possible HRESULT values are listed in the Winerror.h header file. Your app can filter on specific HRESULT values to modify app behavior depending on the cause of the exception.
In apps using the .NET FrameworkВ 4.5 in C#, VB.NET, the System.Exception represents an error during app execution when an exception occurs. The System.Exception.HResult property returns the HRESULT assigned to the specific exception. The System.Exception.Message property returns the message that describes the exception.
C++/CX has been superseded by C++/WinRT. But in apps using C++/CX, the Platform::Exception represents an error during app execution when an exception occurs. The Platform::Exception::HResult property returns the HRESULT assigned to the specific exception. The Platform::Exception::Message property returns the system-provided string that is associated with the HRESULT value.
For most parameter validation errors, the HRESULT returned is E_INVALIDARG. For some illegal method calls, the HRESULT returned is E_ILLEGAL_METHOD_CALL.
Http Client Class
Definition
Provides a class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
Examples
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.
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.
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.
Properties of HttpClient should not be modified while there are outstanding requests, because it is not thread-safe.
The following methods are thread safe:
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.
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, on Windows you can still use WinHttpHandler by referencing it’s NuGet package and passing it to HttpClient ‘s constructor manually.
Configure behavior using run-time configuration options
Certain aspects of HttpClient’s behavior are customizable through Run-time 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.
Constructors
Initializes a new instance of the HttpClient class using a HttpClientHandler that is disposed when this instance is disposed.
Initializes a new instance of the HttpClient class with the specified handler. The handler is disposed when this instance is disposed.
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
Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.
Gets or sets the global Http proxy.
Gets the headers which should be sent with each request.
Gets or sets the default HTTP version used on subsequent requests made by this HttpClient instance.
Gets or sets the default version policy for implicitly created requests in convenience methods, for example, GetAsync(String) and PostAsync(String, HttpContent).
Gets or sets the maximum number of bytes to buffer when reading the response content.
Gets or sets the timespan to wait before the request times out.
Methods
Cancel all pending requests on this instance.
Send a DELETE request to the specified Uri as an asynchronous operation.
Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.
Send a DELETE request to the specified Uri as an asynchronous operation.
Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.
Releases the unmanaged resources and disposes of the managed resources used by the HttpMessageInvoker.
(Inherited from HttpMessageInvoker)
Releases the unmanaged resources used by the HttpClient and optionally disposes of the managed resources.
Determines whether the specified object is equal to the current object.
(Inherited from Object)
Send a GET request to the specified Uri as an asynchronous operation.
Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.
Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation.
Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation.
Send a GET request to the specified Uri as an asynchronous operation.
Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.
Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation.
Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation.
Sends a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.
Sends a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.
Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.
Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.
Serves as the default hash function.
(Inherited from Object)
Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.
Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.
Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.
Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.
Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.
Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.
Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.
Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.
Gets the Type of the current instance.
(Inherited from Object)
Creates a shallow copy of the current Object.
(Inherited from Object)
Sends a PATCH request to a Uri designated as a string as an asynchronous operation.
Sends a PATCH request with a cancellation token to a Uri represented as a string as an asynchronous operation.
Sends a PATCH request as an asynchronous operation.
Sends a PATCH request with a cancellation token as an asynchronous operation.
Send a POST request to the specified Uri as an asynchronous operation.
Send a POST request with a cancellation token as an asynchronous operation.
Send a POST request to the specified Uri as an asynchronous operation.
Send a POST request with a cancellation token as an asynchronous operation.
Send a PUT request to the specified Uri as an asynchronous operation.
Send a PUT request with a cancellation token as an asynchronous operation.
Send a PUT request to the specified Uri as an asynchronous operation.
Send a PUT request with a cancellation token as an asynchronous operation.
Sends an HTTP request with the specified request.
Sends an HTTP request with the specified request and cancellation token.
Sends an HTTP request with the specified request and cancellation token.
(Inherited from HttpMessageInvoker)
Sends an HTTP request.
Sends an HTTP request with the specified request, completion option and cancellation token.
Send an HTTP request as an asynchronous operation.
Send an HTTP request as an asynchronous operation.
Send an HTTP request as an asynchronous operation.
Send an HTTP request as an asynchronous operation.
Returns a string that represents the current object.
(Inherited from Object)
Extension Methods
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.
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.
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.
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.
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.
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.
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.
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.
Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.
Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.
Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.
Sends a POST request to the specified Uri containing the value serialized as JSON in the request body.
Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.
Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.
Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.
Send a PUT request to the specified Uri containing the value serialized as JSON in the request body.