Http​Client Http​Client Http​Client Http​Client 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// You can use this class in JavaScript.
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

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.

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.

Constructors

HttpClient() HttpClient() HttpClient() HttpClient()

Initializes a new instance of the HttpClient class.

public : HttpClient()public HttpClient()Public Sub New()// You can use this method in JavaScript.
See Also

HttpClient(IHttpFilter) 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)// You can use this method in JavaScript.
Parameters
filter
IHttpFilter IHttpFilter IHttpFilter IHttpFilter

The HTTP filter to use for handling response messages.

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);
}

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.

See Also

Methods

Close() 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// You can use this method in JavaScript.

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) 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 )// You can use this method in JavaScript.
Parameters
uri
Uri Uri Uri Uri

The Uri the request is sent to.

Returns

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.

Below are the exceptions that this function throws.

E_INVALIDARG

The uri parameter was null reference (Nothing in Visual Basic).

See Also
UriUriUriUri

Dispose() 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 Disposevoid Dispose()

GetAsync(Uri) 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 )// You can use this method in JavaScript.
Parameters
uri
Uri Uri Uri Uri

The Uri to which the request is to be sent.

Returns

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.

Below are the exceptions that this function throws.

COMException

Thrown when a feature-specific HRESULT is returned from a method call.

This is the most common exception that is thrown by networking methods. An app should use the HRESULT from the exception to determine the cause of the error.

AccessDeniedException

Thrown when access is denied to a resource or feature. This exception occurs when an app doesn't have the required network capabilities set in the app manifest for the network operation requested.

InvalidArgumentException

Thrown when one of the arguments that are provided to a method is not valid.

If user-supplied input caused this exception, an app could inform the user and request new input.

ObjectDisposedException

Thrown when an operation is performed on a disposed object.

OutOfMemoryException

Thrown when insufficient memory is available to complete the operation.

See Also

GetAsync(Uri, HttpCompletionOption) 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 )// You can use this method in JavaScript.
Parameters
uri
Uri Uri Uri Uri

The Uri the request is sent to.

completionOption
HttpCompletionOption HttpCompletionOption HttpCompletionOption HttpCompletionOption

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

Returns

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.

Below are the exceptions that this content throws.

COMException

Thrown when a feature-specific HRESULT is returned from a method call.

This is the most common exception that is thrown by networking methods. An app should use the HRESULT from the exception to determine the cause of the error.

AccessDeniedException

Thrown when access is denied to a resource or feature. This exception occurs when an app doesn't have the required network capabilities set in the app manifest for the network operation requested.

InvalidArgumentException

Thrown when one of the arguments that are provided to a method is not valid.

If user-supplied input caused this exception, an app could inform the user and request new input.

ObjectDisposedException

Thrown when an operation is performed on a disposed object.

OutOfMemoryException

Thrown when insufficient memory is available to complete the operation.

See Also

GetBufferAsync(Uri) 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 )// You can use this method in JavaScript.
Parameters
uri
Uri Uri Uri Uri

The Uri the request is sent to.

Returns

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.

Below are the exceptions that this function throws.

E_INVALIDARG

The uri parameter was a null reference (Nothing in Visual Basic).

See Also
UriUriUriUri

GetInputStreamAsync(Uri) 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 )// You can use this method in JavaScript.
Parameters
uri
Uri Uri Uri Uri

The Uri the request is sent to.

Returns

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.

Below are the exceptions that this function throws.

E_INVALIDARG

The uri parameter was a null reference (Nothing in Visual Basic).

See Also
UriUriUriUri

GetStringAsync(Uri) 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<PlatForm::String, HttpProgress> GetStringAsync(Uri uri)public IAsyncOperationWithProgress<string, HttpProgress> GetStringAsync(Uri uri)Public Function GetStringAsync(uri As Uri) As IAsyncOperationWithProgress( Of string, HttpProgress )// You can use this method in JavaScript.
Parameters
uri
Uri Uri Uri Uri

The Uri the request is sent to.

Returns

The object representing the asynchronous operation.

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.

Below are the exceptions that this function throws.

E_INVALIDARG

The uri parameter was a null reference (Nothing in Visual Basic).

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.

See Also
UriUriUriUri

PostAsync(Uri, IHttpContent) 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 )// You can use this method in JavaScript.
Parameters
uri
Uri Uri Uri Uri

The Uri the request is sent to.

content
IHttpContent IHttpContent IHttpContent IHttpContent

The HTTP request content to send to the server.

Returns

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.

Below are the exceptions that this function throws.

E_INVALIDARG

The uri parameter was a null reference (Nothing in Visual Basic).

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.

See Also

PutAsync(Uri, IHttpContent) 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 )// You can use this method in JavaScript.
Parameters
uri
Uri Uri Uri Uri

The Uri the request is sent to.

content
IHttpContent IHttpContent IHttpContent IHttpContent

The HTTP request content to send to the server.

Returns

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.

Below are the exceptions that this function throws.

E_INVALIDARG

The uri parameter was a null reference (Nothing in Visual Basic).

See Also

SendRequestAsync(HttpRequestMessage) 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 )// You can use this method in JavaScript.
Parameters
Returns

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.

Below are the exceptions that this function throws.

E_INVALIDARG

The request parameter was a null reference (Nothing in Visual Basic).

E_ILLEGAL_METHOD_CALL

The request message was already sent by the HttpClient instance.

See Also

SendRequestAsync(HttpRequestMessage, HttpCompletionOption) 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 )// You can use this method in JavaScript.
Parameters
completionOption
HttpCompletionOption 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

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.

Below are the exceptions that this function throws.

E_INVALIDARG

The request parameter was a null reference (Nothing in Visual Basic).

E_ILLEGAL_METHOD_CALL

The request message was already sent by the HttpClient instance.

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.

See Also

ToString() ToString() ToString() ToString()

Returns a string that represents the current HttpClient object.

public : PlatForm::String ToString()public string ToString()Public Function ToString() As string// You can use this method in JavaScript.
Returns
PlatForm::String string string string

A string that represents the current object.

See Also