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

Methods

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

HttpResponseMessage

Represents an HTTP response. Contains status code, headers, and content.

Properties

Methods

HttpContent

Represents the HTTP content of a request or response. This is an abstract base class. Concrete implementations include:

Note: Always ensure you dispose of 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.

Important: For most applications, relying on the default SSL/TLS certificate validation is the most secure approach. Avoid disabling certificate validation unless absolutely necessary and you fully understand the risks.