HttpClient HttpClient HttpClient HttpClient Class

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

Syntax

Declaration

public sealed class HttpClientpublic sealed class HttpClientPublic NotInheritable Class HttpClient

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(Windows.Foundation.Uri) 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(Windows.Foundation.Uri) 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 summary

Initializes a new instance of the HttpClient class.

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

Properties summary

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

Methods summary

Closes the HttpClient instance and releases allocated resources.

Send a DELETE request to the specified Uri 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 an HTTP completion option as an asynchronous operation.

Send a GET request to the specified Uri and return the response body as a buffer 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 POST request to the specified Uri as an asynchronous operation.

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

Send an HTTP request as an asynchronous operation.

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

Returns a string that represents the current HttpClient object.

Constructors

  • HttpClient()
    HttpClient()
    HttpClient()
    HttpClient()

    Initializes a new instance of the HttpClient class.

    public HttpClient()public HttpClient()Public Function HttpClient() As
  • HttpClient(Windows.Web.Http.Filters.IHttpFilter)
    HttpClient(Windows.Web.Http.Filters.IHttpFilter)
    HttpClient(Windows.Web.Http.Filters.IHttpFilter)
    HttpClient(Windows.Web.Http.Filters.IHttpFilter)

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

    public HttpClient(Windows.Web.Http.Filters.IHttpFilter)public HttpClient(Windows.Web.Http.Filters.IHttpFilter)Public Function HttpClient(Windows.Web.Http.Filters.IHttpFilter) As

    Parameters

    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
    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

    Property Value

    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(Windows.Foundation.Uri,Windows.Web.Http.HttpCompletionOption). 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()
    Close()

    Closes the HttpClient instance and releases allocated resources.

    public void Close()public void Close()Public Function Close() As void

    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(Windows.Foundation.Uri)
    DeleteAsync(Windows.Foundation.Uri)
    DeleteAsync(Windows.Foundation.Uri)
    DeleteAsync(Windows.Foundation.Uri)

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

    public IAsyncOperationWithProgress<HttpProgress> DeleteAsync(Windows.Foundation.Uri)public IAsyncOperationWithProgress<HttpProgress> DeleteAsync(Windows.Foundation.Uri)Public Function DeleteAsync(Windows.Foundation.Uri) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

    This operation will not block. The returned IAsyncOperationWithProgress<TResult, TProgress> 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.

  • GetAsync(Windows.Foundation.Uri)
    GetAsync(Windows.Foundation.Uri)
    GetAsync(Windows.Foundation.Uri)
    GetAsync(Windows.Foundation.Uri)

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

    public IAsyncOperationWithProgress<HttpProgress> GetAsync(Windows.Foundation.Uri)public IAsyncOperationWithProgress<HttpProgress> GetAsync(Windows.Foundation.Uri)Public Function GetAsync(Windows.Foundation.Uri) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

    This operation will not block. The returned IAsyncOperationWithProgress<TResult, TProgress> 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(Windows.Foundation.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(Windows.Foundation.Uri) to connect to an HTTP server and send a GET request, see Connecting to an HTTP server using Windows.Web.Http.

  • GetAsync(Windows.Foundation.Uri,Windows.Web.Http.HttpCompletionOption)
    GetAsync(Windows.Foundation.Uri,Windows.Web.Http.HttpCompletionOption)
    GetAsync(Windows.Foundation.Uri,Windows.Web.Http.HttpCompletionOption)
    GetAsync(Windows.Foundation.Uri,Windows.Web.Http.HttpCompletionOption)

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

    public IAsyncOperationWithProgress<HttpProgress> GetAsync(Windows.Foundation.Uri,Windows.Web.Http.HttpCompletionOption)public IAsyncOperationWithProgress<HttpProgress> GetAsync(Windows.Foundation.Uri,Windows.Web.Http.HttpCompletionOption)Public Function GetAsync(Windows.Foundation.Uri,Windows.Web.Http.HttpCompletionOption) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

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

  • GetBufferAsync(Windows.Foundation.Uri)
    GetBufferAsync(Windows.Foundation.Uri)
    GetBufferAsync(Windows.Foundation.Uri)
    GetBufferAsync(Windows.Foundation.Uri)

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

    public IAsyncOperationWithProgress<HttpProgress> GetBufferAsync(Windows.Foundation.Uri)public IAsyncOperationWithProgress<HttpProgress> GetBufferAsync(Windows.Foundation.Uri)Public Function GetBufferAsync(Windows.Foundation.Uri) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

    This operation will not block. The returned IAsyncOperationWithProgress<TResult, TProgress> 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(Windows.Foundation.Uri) 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(Windows.Foundation.Uri) 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(Windows.Foundation.Uri)
    GetInputStreamAsync(Windows.Foundation.Uri)
    GetInputStreamAsync(Windows.Foundation.Uri)
    GetInputStreamAsync(Windows.Foundation.Uri)

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

    public IAsyncOperationWithProgress<HttpProgress> GetInputStreamAsync(Windows.Foundation.Uri)public IAsyncOperationWithProgress<HttpProgress> GetInputStreamAsync(Windows.Foundation.Uri)Public Function GetInputStreamAsync(Windows.Foundation.Uri) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

    This operation will not block. The returned IAsyncOperationWithProgress<TResult, TProgress> 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(Windows.Foundation.Uri)
    GetStringAsync(Windows.Foundation.Uri)
    GetStringAsync(Windows.Foundation.Uri)
    GetStringAsync(Windows.Foundation.Uri)

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

    public IAsyncOperationWithProgress<HttpProgress> GetStringAsync(Windows.Foundation.Uri)public IAsyncOperationWithProgress<HttpProgress> GetStringAsync(Windows.Foundation.Uri)Public Function GetStringAsync(Windows.Foundation.Uri) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

    This operation will not block. The returned IAsyncOperationWithProgress<TResult, TProgress> 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(Windows.Foundation.Uri) 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(Windows.Foundation.Uri) 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(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)
    PostAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)
    PostAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)
    PostAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)

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

    public IAsyncOperationWithProgress<HttpProgress> PostAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)public IAsyncOperationWithProgress<HttpProgress> PostAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)Public Function PostAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

    This operation will not block. The returned IAsyncOperationWithProgress<TResult, TProgress> object will complete after the whole response (including content) is read.

    The PostAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent) and PutAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent) methods only allow setting a limited number of HTTP content headers. In contrast, the SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption) 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(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)
    PutAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)
    PutAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)
    PutAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)

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

    public IAsyncOperationWithProgress<HttpProgress> PutAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)public IAsyncOperationWithProgress<HttpProgress> PutAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent)Public Function PutAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

    This operation will not block. The returned IAsyncOperationWithProgress<TResult, TProgress> object will complete after the whole response (including content) is read.

    The PutAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent) and PostAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent) methods only allow setting a limited number of HTTP content headers. In contrast, the SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption) method allows setting headers on the request message as well as on the HTTP content to be sent.

  • SendRequestAsync(Windows.Web.Http.HttpRequestMessage)
    SendRequestAsync(Windows.Web.Http.HttpRequestMessage)
    SendRequestAsync(Windows.Web.Http.HttpRequestMessage)
    SendRequestAsync(Windows.Web.Http.HttpRequestMessage)

    Send an HTTP request as an asynchronous operation.

    public IAsyncOperationWithProgress<HttpProgress> SendRequestAsync(Windows.Web.Http.HttpRequestMessage)public IAsyncOperationWithProgress<HttpProgress> SendRequestAsync(Windows.Web.Http.HttpRequestMessage)Public Function SendRequestAsync(Windows.Web.Http.HttpRequestMessage) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

    This operation will not block. The returned IAsyncOperationWithProgress<TResult, TProgress> object will complete after the whole response (including content) is read.

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

  • SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption)
    SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption)
    SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption)
    SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption)

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

    public IAsyncOperationWithProgress<HttpProgress> SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption)public IAsyncOperationWithProgress<HttpProgress> SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption)Public Function SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption) As IAsyncOperationWithProgress( Of HttpProgress )

    Parameters

    Returns

    • The object representing the asynchronous operation.

    Remarks

    This operation will not block. The returned IAsyncOperationWithProgress<TResult, TProgress> object will complete depending on the value of the completionOption parameter.

    The HttpRequestMessage passed in the request parameter allows the SendRequestAsync(Windows.Web.Http.HttpRequestMessage,Windows.Web.Http.HttpCompletionOption) method to set headers on the request message as well as on the HTTP content to be sent. In contrast, the PostAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent) and PutAsync(Windows.Foundation.Uri,Windows.Web.Http.IHttpContent) 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()
    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
      string

      A string that represents the current object.

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.ActivatableAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.DualApiPartitionAttribute
Windows.Foundation.Metadata.ThreadingAttribute
Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.ActivatableAttribute

Details

Assembly

Windows.Web.Http.dll