HTTP API Reference
This section provides details on the Windows Runtime (WinRT) APIs for making HTTP requests in Universal Windows Platform (UWP) applications.
Core Classes
The primary classes for interacting with HTTP are found in the Windows.Web.Http namespace.
HttpClient
The HttpClient class represents a session for sending HTTP requests and receiving HTTP responses. It is the main entry point for most HTTP operations.
Properties
DefaultRequestHeaders: Gets the default HTTP headers that are sent with every request.MaxHttpCollectionLength: Gets or sets the maximum number of HTTP connections that can be pooled.DefaultTimeout: Gets or sets the default timeout for operations.
Methods
GetAsync(Uri uri): Sends a GET request to the specified URI and returns the response.PostAsync(Uri uri, IHttpContent content): Sends a POST request to the specified URI with the given content.PutAsync(Uri uri, IHttpContent content): Sends a PUT request.DeleteAsync(Uri uri): Sends a DELETE request.SendRequestAsync(HttpRequestMessage request)`: Sends an arbitrary HTTP request.
Example: Making a GET Request
using Windows.Web.Http;
using System;
using System.Threading.Tasks;
public class HttpExample
{
public async Task MakeGetRequestAsync()
{
using (var httpClient = new HttpClient())
{
var uri = new Uri("https://jsonplaceholder.typicode.com/posts/1");
try
{
HttpResponseMessage response = await httpClient.GetAsync(uri);
response.EnsureSuccessStatusCode(); // Throws if the status code is not success
string responseBody = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(responseBody);
}
catch (HttpRequestException ex)
{
System.Diagnostics.Debug.WriteLine($"Request error: {ex.Message}");
}
}
}
}
HttpRequestMessage
Represents an HTTP request. You can customize the method, URI, headers, and content.
Properties
Method: The HTTP method (e.g., GET, POST).RequestUri: The URI to send the request to.Content: The HTTP content to send with the request.Headers: The collection of HTTP request headers.
HttpResponseMessage
Represents an HTTP response. Contains status code, headers, and content.
Properties
StatusCode: The HTTP status code.ReasonPhrase: The reason phrase for the status code.Content: The HTTP content received in the response.Headers: The collection of HTTP response headers.
Methods
EnsureSuccessStatusCode(): Throws an exception if the HTTP status code indicates an error.Content.ReadAsStringAsync(): Reads the response content as a string.Content.ReadAsBufferAsync(): Reads the response content as a buffer.
HttpContent
Represents the HTTP content of a request or response. This is an abstract base class. Concrete implementations include:
StringContent: For sending plain text or JSON/XML strings.StreamContent: For sending data from a stream.ByteArrayContent: For sending a byte array.MultipartFormDataContent: For sending multipart/form-data.
HttpClient and HttpResponseMessage instances, typically by using a using statement to release network resources efficiently.
Common Scenarios
Sending JSON Data
Use StringContent with the application/json media type.
using Windows.Web.Http;
using System;
using System.Text.Json; // Or Newtonsoft.Json
public class JsonExample
{
public async Task SendJsonPostAsync()
{
using (var httpClient = new HttpClient())
{
var uri = new Uri("https://jsonplaceholder.typicode.com/posts");
var postData = new { title = "foo", body = "bar", userId = 1 };
string jsonString = JsonSerializer.Serialize(postData); // Or Newtonsoft.Json.JsonConvert.SerializeObject(postData);
using (var content = new StringContent(jsonString, System.Text.Encoding.UTF8, "application/json"))
{
HttpResponseMessage response = await httpClient.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(responseBody);
}
}
}
}
Handling Request Headers
You can set common headers on the HttpClient or specific request headers on the HttpRequestMessage.
// Setting default headers
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("MyUWPApp/1.0");
httpClient.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("application/json"));
// Setting request-specific headers
var request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Add("X-Custom-Header", "MyValue");
var response = await httpClient.SendRequestAsync(request);
Handling Redirects
The HttpClient automatically follows redirects by default. You can control this behavior using HttpClient.DefaultRequestHeaders.FollowRedirects.
Security Considerations
For secure communication, always use HTTPS URIs and ensure your application has the necessary capabilities declared in its manifest (e.g., Internet (Client & Server)).
SSL/TLS Certificates
The HttpClient validates SSL/TLS certificates by default. You can optionally configure custom certificate validation callbacks using HttpClient.DefaultRequestHeaders.SetRequestHeader(HttpClient.CertificateValidationHeaderName, "true") and handling the ServerCustomValidation event, though this is generally not recommended unless you have specific security requirements.