HttpClient Class
Namespace: Windows.Networking.Http
Represents a Windows Store app that can send HTTP requests and receive HTTP responses.
Syntax
public ref class HttpClient
sealed
: IClosable
Members
The HttpClient class has the following members.
Constructors
| Name | Description |
|---|---|
HttpClient() |
Initializes a new instance of the HttpClient class. |
HttpClient(HttpBufferContent content) |
Initializes a new instance of the HttpClient class with the specified content. |
Methods
| Name | Description |
|---|---|
DeleteAsync(Uri uri) |
Sends a DELETE request to the specified URI. |
GetAsync(Uri uri) |
Sends a GET request to the specified URI. |
GetInputStreamResultAsync(Uri uri) |
Sends a GET request to the specified URI and returns the response body as an input stream. |
PutAsync(Uri uri, HttpContent content) |
Sends a PUT request to the specified URI with the specified content. |
SendRequestAsync(HttpRequestMessage request) |
Sends an HTTP request to the server and returns the HTTP response. |
Dispose() |
Releases the resources used by the HttpClient object. |
Properties
| Name | Description |
|---|---|
DefaultRequestHeaders |
Gets a collection of HTTP HTTPRequestHeaderCollection that are sent with every request. |
MaxHttpCollectionCount |
Gets or sets the maximum number of HTTP connections to the same server that can be made. |
Examples
Getting a web page
This example shows how to use HttpClient to get the content of a web page.
using Windows.Networking.Http;
using Windows.Foundation;
using System;
using System.Threading.Tasks;
public async Task<string> GetWebPageAsync(string url)
{
using (var httpClient = new HttpClient())
{
try
{
// Set a timeout for the request (optional)
httpClient.Timeout = TimeSpan.FromSeconds(20);
// Add a default header (optional)
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("MyUWPApp/1.0");
// Send the GET request
var httpResponse = await httpClient.GetAsync(new Uri(url));
httpResponse.EnsureSuccessStatusCode(); // Throws if the status code is not 2xx
// Read the response content as a string
var responseBody = await httpResponse.Content.ReadAsStringAsync();
return responseBody;
}
catch (Exception ex)
{
// Handle exceptions (e.g., network errors, invalid URI)
System.Diagnostics.Debug.WriteLine($"Error fetching {url}: {ex.Message}");
return null;
}
}
}