HttpClient HttpClient HttpClient Class

Definition

Sends HTTP requests and receives HTTP responses from a resource identified by a URI.

public sealed class HttpClient : IClosable, IStringable, IHttpClientpublic sealed class HttpClient : IDisposable, IStringable, IHttpClientPublic NotInheritable Class HttpClient Implements IDisposable, IStringable, IHttpClient
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

Remarks

The HttpClient class instance acts as a session to send HTTP requests and receive responses. An HttpClient instance is a collection of settings that apply 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 class to use with filters for more specific HTTP clients. An example would be an HttpClientFilter that provides additional methods specific to a social network service (a GetFriends method, for instance).

If an app using HttpClient and related classes in the Windows.Web.Http namespace downloads 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 reduced performance.

For sample code in C#/VB/C++ and XAML that shows how to use HttpClient to connect to an HTTP server, see HttpClient.

For sample code in JavaScript and HTML that shows how to use HttpClient to connect to an HTTP server, see Connecting to an HTTP server using Windows.Web.Http.

Examples

The following sample code shows how to GET content from a Web server as a string.

var uri = new Uri("http://example.com/datalist.aspx");
var httpClient = new HttpClient();

// Always catch network exceptions for async methods
httpClient.GetStringAsync(uri).done(function () {
    // get completed
    }, onError);


function onError(reason) {
    // Details in reason.Message and ex.HResult.       
}

// Once your app is done using the HttpClient object call close to 
// free up system resources (the underlying socket and memory used for the object)
// httpClient.close();

using System;
using Windows.Foundation;
using Windows.Web.Http;

var uri = new Uri("http://example.com/datalist.aspx");
var httpClient = new HttpClient();

// Always catch network exceptions for async methods
try 
{
    var result = await httpClient.GetStringAsync(uri);
}
catch 
{
    // Details in ex.Message and ex.HResult.       
}

// Once your app is done using the HttpClient object call dispose to 
// free up system resources (the underlying socket and memory used for the object)
httpclient.Dispose();

using namespace Windows::Foundation;
using namespace Windows::Web::Http;

uri = ref new Uri("http://example.com/datalist.aspx");
httpClient = ref new HttpClient();

// Always catch network exceptions for async methods
try 
{
    httpClient->GetStringAsync(uri);
}
catch 
{
    // Details in ex.Message and ex.HResult.       
}

// In C++ and CX, the system resources used by httpClient object are released 
// when the object falls out of scope or by the destructor (delete operator)

The HttpClient class is often used by an app to download and then parse text. It is possible that the character encoding specified in the Content-Type header by an HTTP server does not match the character encoding of the HTTP response body (the XML encoding in an XML document, for example). One way to use HttpClient with text is to call the GetStringAsync method and pass the returned string to the text parser. However, this can result in errors if the Content-Type is not a type expressible as a string. A reliable way to use HttpClient with an XML parser is to call the GetBufferAsync method and parse the buffer for the "<?xml>" element. Then use the character encoding specified ("<xmlversion="1.0" encoding="UTF-8"?>", for example) to parse the HTTP response body. For other text formats, similar methods can be used where the app scans the initial part of the HTTP response body to determine the character encoding used.

Constructors

HttpClient() HttpClient() HttpClient()

Initializes a new instance of the HttpClient class.

public HttpClient()public HttpClient()Public Sub New()
Attributes

HttpClient(IHttpFilter) HttpClient(IHttpFilter) HttpClient(IHttpFilter)

Initializes a new instance of the HttpClient class with a specific filter for handling HTTP response messages.

public HttpClient(IHttpFilter filter)public HttpClient(IHttpFilter filter)Public Sub New(filter As IHttpFilter)
Parameters
filter
IHttpFilter IHttpFilter IHttpFilter

The HTTP filter to use for handling response messages.

Attributes

Remarks

If a null reference (Nothing in Visual Basic) is specified for the filter parameter, the default transport handler for receiving responses with no filter is used.

Examples

The sample code shows creating an HttpClient to use a custom filter.


internal static void CreateHttpClient(ref HttpClient httpClient)
{
    if (httpClient != null) {
        httpClient.Dispose();
    }

    // HttpClient can be extended by plugging multiple filters together,
    // providing HttpClient with the configured filter pipeline.
    var baseFilter = new HttpBaseProtocolFilter();

    var myFilter = new MyCustomFilter(baseFilter);
    httpClient = new HttpClient(myFilter);
}

Properties

DefaultRequestHeaders DefaultRequestHeaders DefaultRequestHeaders

Gets a collection of headers that should be sent with each request.

public HttpRequestHeaderCollection DefaultRequestHeaders { get; }public HttpRequestHeaderCollection DefaultRequestHeaders { get; }Public ReadOnly Property DefaultRequestHeaders As HttpRequestHeaderCollection
Value
HttpRequestHeaderCollection HttpRequestHeaderCollection HttpRequestHeaderCollection

The headers that should be sent with each request.

Attributes

Remarks

The DefaultRequestHeaders property returns an HttpRequestHeaderCollection object that can be used to get or set the specific headers on the HttpClient instance. HTTP headers set on this property will be sent on all request messages sent on this HttpClient instance and don't need to be set on each HttpRequestMessage instance.

The Headers property on the HttpRequestMessage object returns an HttpRequestHeaderCollection object that can be used to get or set the specific headers on a specific HTTP request.

The DefaultRequestHeaders property represents the headers that an app developer can set, not all of the headers that may eventually be sent with the request. The HttpBaseProtocolFilter will add some additional headers.

Warning

In versions before Windows 10, setting certain headers to NULL caused an empty header value to be set, which caused an unexpected failure in subsequent calls to GetAsync. Starting in Windows 10, setting any of the following headers to NULL causes them to be removed from the request entirely, so that the remaining headers are valid.

  • Authorization
  • Date
  • From
  • Host
  • If-Modified-Since
  • If-Unmodified-Since
  • Max-Forwards
  • Proxy-Authorization
  • Referer If you are writing for versions before Windows 10, do not set these header values to NULL.

Methods

Close() Close() Close()

Closes the HttpClient instance and releases allocated resources.

public void Close()This member is not implemented in C#This member is not implemented in VB.Net
Attributes

Remarks

The Close method releases allocated resources used by the HttpClient instance. The Close method can manage the lifetime of system resources (the underlying socket and memory for the HttpClient, for example) used by a Windows Runtime object.

In the .NET Framework 4.5, this method projects as the Dispose method. In Visual C++ component extensions (C++/CX), this method projects as the destructor (delete operator).

Apps written in JavaScript, C#, or VB.NET use garbage collection to release resources. So the HttpClient object and associated resources doesn't get released until the garbage collection pass runs. The Close method allows an app to release these resources early rather than waiting for the object to be released by garbage collection.

Apps written in C++ or CX don't have a Close method since these apps can destroy the object. In C++ and CX, objects are released when they fall out of program scope or as part of the destructor (delete operator) for the object.

DeleteAsync(Uri) DeleteAsync(Uri) DeleteAsync(Uri)

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

public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> DeleteAsync(Uri uri)public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> DeleteAsync(Uri uri)Public Function DeleteAsync(uri As Uri) As IAsyncOperationWithProgress( Of HttpResponseMessage, HttpProgress )
Parameters
uri
Uri Uri Uri

The Uri the request is sent to.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(HttpResponseMessage, HttpProgress) object will complete after the whole response (including content) is read.

Exception Handling

You must write code to handle exceptions when you call this method. Exceptions can result from parameter validation errors, name resolutions failures, and network errors. Exceptions from network errors (loss of connectivity, connection failures, and HTTP server failures, for example) can happen at any time. These errors result in exceptions being thrown. If not handled by your app, an exception can cause your entire app to be terminated by the runtime. For more information on how to handle exceptions, see Handling exceptions in network apps.

Dispose() Dispose() Dispose()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

This member is not implemented in C++void Dispose()Sub Dispose
Attributes

GetAsync(Uri) GetAsync(Uri) GetAsync(Uri)

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

public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> GetAsync(Uri uri)public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> GetAsync(Uri uri)Public Function GetAsync(uri As Uri) As IAsyncOperationWithProgress( Of HttpResponseMessage, HttpProgress )
Parameters
uri
Uri Uri Uri

The Uri to which the request is to be sent.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(HttpResponseMessage, HttpProgress) object will complete after the whole response (including content) is read.

For sample code in C#/VB/C++ and XAML that shows how to use HttpClient and GetAsync(Uri) to connect to an HTTP server and send a GET request, see HttpClient.

For sample code in JavaScript and HTML that shows how to use HttpClient and GetAsync(Uri) to connect to an HTTP server and send a GET request, see Connecting to an HTTP server using Windows.Web.Http.

GetAsync(Uri, HttpCompletionOption) GetAsync(Uri, HttpCompletionOption) GetAsync(Uri, HttpCompletionOption)

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

public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> GetAsync(Uri uri, HttpCompletionOption completionOption)public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> GetAsync(Uri uri, HttpCompletionOption completionOption)Public Function GetAsync(uri As Uri, completionOption As HttpCompletionOption) As IAsyncOperationWithProgress( Of HttpResponseMessage, HttpProgress )
Parameters
uri
Uri Uri Uri

The Uri the request is sent to.

completionOption
HttpCompletionOption HttpCompletionOption HttpCompletionOption

An HTTP completion option value that indicates when the operation should be considered completed.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(HttpResponseMessage, HttpProgress) object will complete based on the completionOption parameter after part or all of the response (including content) is read.

See Also

GetBufferAsync(Uri) GetBufferAsync(Uri) GetBufferAsync(Uri)

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

public IAsyncOperationWithProgress<IBuffer, HttpProgress> GetBufferAsync(Uri uri)public IAsyncOperationWithProgress<IBuffer, HttpProgress> GetBufferAsync(Uri uri)Public Function GetBufferAsync(uri As Uri) As IAsyncOperationWithProgress( Of IBuffer, HttpProgress )
Parameters
uri
Uri Uri Uri

The Uri the request is sent to.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(IBuffer, HttpProgress) object will complete after the whole response body is read.

The HttpClient class is often used by an app to download and then parse text. It is possible that the character encoding specified in the Content-Type header by an HTTP server does not match the character encoding of the HTTP response body (the XML encoding in an XML document, for example). One way to use HttpClient with text is to call the GetStringAsync method and pass the returned string to the text parser. However, this can result in errors if the Content-Type is not a type expressible as a string. A reliable way to use HttpClient with an XML parser is to call the GetBufferAsync method and parse the buffer for the "<?xml>" element. Then use the character encoding specified ("<xmlversion="1.0" encoding="UTF-8"?>", for example) to parse the HTTP response body. For other text formats, similar methods can be used where the app scans the initial part of the HTTP response body to determine the character encoding used.

GetInputStreamAsync(Uri) GetInputStreamAsync(Uri) GetInputStreamAsync(Uri)

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

public IAsyncOperationWithProgress<IInputStream, HttpProgress> GetInputStreamAsync(Uri uri)public IAsyncOperationWithProgress<IInputStream, HttpProgress> GetInputStreamAsync(Uri uri)Public Function GetInputStreamAsync(uri As Uri) As IAsyncOperationWithProgress( Of IInputStream, HttpProgress )
Parameters
uri
Uri Uri Uri

The Uri the request is sent to.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(IInputStream, HttpProgress) object will complete after the whole response body is read. This method does not buffer the stream, so this method can support long streams of arbitrary length.

GetStringAsync(Uri) GetStringAsync(Uri) GetStringAsync(Uri)

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

public IAsyncOperationWithProgress<string, HttpProgress> GetStringAsync(Uri uri)public IAsyncOperationWithProgress<string, HttpProgress> GetStringAsync(Uri uri)Public Function GetStringAsync(uri As Uri) As IAsyncOperationWithProgress( Of string, HttpProgress )
Parameters
uri
Uri Uri Uri

The Uri the request is sent to.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(String, HttpProgress) object will complete after the whole response body is read.

The HttpClient class is often used by an app to download and then parse text. It is possible that the character encoding specified in the Content-Type header by an HTTP server does not match the character encoding of the HTTP response body (the XML encoding in an XML document, for example). One way to use HttpClient with text is to call the GetStringAsync method and pass the returned string to the text parser. However, this can result in errors if the Content-Type is not a type expressible as a string. A reliable way to use HttpClient with an XML parser is to call the GetBufferAsync method and parse the buffer for the "<?xml>" element. Then use the character encoding specified ("<xmlversion="1.0" encoding="UTF-8"?>", for example) to parse the HTTP response body. For other text formats, similar methods can be used where the app scans the initial part of the HTTP response body to determine the character encoding used.

Exception Handling

You must write code to handle exceptions when you call this method. Exceptions can result from parameter validation errors, name resolutions failures, and network errors. Exceptions from network errors (loss of connectivity, connection failures, and HTTP server failures, for example) can happen at any time. These errors result in exceptions being thrown. If not handled by your app, an exception can cause your entire app to be terminated by the runtime. For more information on how to handle exceptions, see Handling exceptions in network apps.

PostAsync(Uri, IHttpContent) PostAsync(Uri, IHttpContent) PostAsync(Uri, IHttpContent)

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

public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> PostAsync(Uri uri, IHttpContent content)public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> PostAsync(Uri uri, IHttpContent content)Public Function PostAsync(uri As Uri, content As IHttpContent) As IAsyncOperationWithProgress( Of HttpResponseMessage, HttpProgress )
Parameters
uri
Uri Uri Uri

The Uri the request is sent to.

content
IHttpContent IHttpContent IHttpContent

The HTTP request content to send to the server.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(HttpResponseMessage, HttpProgress) object will complete after the whole response (including content) is read.

The PostAsync and PutAsync methods only allow setting a limited number of HTTP content headers. In contrast, the SendRequestAsync method allows setting headers on the request message as well as on the HTTP content to be sent.

Exception Handling

You must write code to handle exceptions when you call this method. Exceptions can result from parameter validation errors, name resolutions failures, and network errors. Exceptions from network errors (loss of connectivity, connection failures, and HTTP server failures, for example) can happen at any time. These errors result in exceptions being thrown. If not handled by your app, an exception can cause your entire app to be terminated by the runtime. For more information on how to handle exceptions, see Handling exceptions in network apps.

PutAsync(Uri, IHttpContent) PutAsync(Uri, IHttpContent) PutAsync(Uri, IHttpContent)

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

public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> PutAsync(Uri uri, IHttpContent content)public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> PutAsync(Uri uri, IHttpContent content)Public Function PutAsync(uri As Uri, content As IHttpContent) As IAsyncOperationWithProgress( Of HttpResponseMessage, HttpProgress )
Parameters
uri
Uri Uri Uri

The Uri the request is sent to.

content
IHttpContent IHttpContent IHttpContent

The HTTP request content to send to the server.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(HttpResponseMessage, HttpProgress) object will complete after the whole response (including content) is read.

The PutAsync and PostAsync methods only allow setting a limited number of HTTP content headers. In contrast, the SendRequestAsync method allows setting headers on the request message as well as on the HTTP content to be sent.

SendRequestAsync(HttpRequestMessage) SendRequestAsync(HttpRequestMessage) SendRequestAsync(HttpRequestMessage)

Send an HTTP request as an asynchronous operation.

public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)Public Function SendRequestAsync(request As HttpRequestMessage) As IAsyncOperationWithProgress( Of HttpResponseMessage, HttpProgress )
Parameters
request
HttpRequestMessage HttpRequestMessage HttpRequestMessage

The HTTP request message to send.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(HttpResponseMessage, HttpProgress) object will complete after the whole response (including content) is read.

The HttpRequestMessage passed in the request parameter allows the SendRequestAsync method to set headers on the request message as well as on the HTTP content to be sent. In contrast, the PostAsync and PutAsync methods only allow setting a more limited set of HTTP content headers.

SendRequestAsync(HttpRequestMessage, HttpCompletionOption) SendRequestAsync(HttpRequestMessage, HttpCompletionOption) SendRequestAsync(HttpRequestMessage, HttpCompletionOption)

Send an HTTP request with an HTTP completion option as an asynchronous operation.

public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request, HttpCompletionOption completionOption)public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request, HttpCompletionOption completionOption)Public Function SendRequestAsync(request As HttpRequestMessage, completionOption As HttpCompletionOption) As IAsyncOperationWithProgress( Of HttpResponseMessage, HttpProgress )
Parameters
request
HttpRequestMessage HttpRequestMessage HttpRequestMessage

The HTTP request message to send.

completionOption
HttpCompletionOption HttpCompletionOption HttpCompletionOption

A value that indicates whether the HttpClient operation is considered completed when all of the response is read, or when just the headers are read.

Returns

The object representing the asynchronous operation.

Attributes

Remarks

This operation will not block. The returned IAsyncOperationWithProgress(HttpResponseMessage, HttpProgress) object will complete depending on the value of the completionOption parameter.

The HttpRequestMessage passed in the request parameter allows the SendRequestAsync method to set headers on the request message as well as on the HTTP content to be sent. In contrast, the PostAsync and PutAsync methods only allow setting a more limited set of HTTP content headers.

Exception Handling

You must write code to handle exceptions when you call this method. Exceptions can result from parameter validation errors, name resolutions failures, and network errors. Exceptions from network errors (loss of connectivity, connection failures, and HTTP server failures, for example) can happen at any time. These errors result in exceptions being thrown. If not handled by your app, an exception can cause your entire app to be terminated by the runtime. For more information on how to handle exceptions, see Handling exceptions in network apps.

ToString() ToString() ToString()

Returns a string that represents the current HttpClient object.

public string ToString()public string ToString()Public Function ToString() As string
Returns
string string string

A string that represents the current object.

Attributes

See Also