Provides a programming model for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. This class handles the details of HTTP communication, including managing connections, cookies, and authentication.
| Signature | Description |
|---|---|
HttpClientHandler()
|
Initializes a new instance of the HttpClientHandler class.
|
| Name | Type | Description |
|---|---|---|
AllowAutoRedirect |
bool |
Gets or sets a value that indicates whether the HTTP handler should automatically follow redirection responses (e.g., HTTP 3xx). Default is true. |
AutomaticDecompression |
DecompressionMethods |
Gets or sets a value that indicates whether the HTTP client supports automatic decompression of supported responses. Default is DecompressionMethods.GZip | DecompressionMethods.Deflate. |
ClientCertificateOptions |
ClientCertificateOption |
Gets or sets a value that indicates how the client certificate is provided. |
CookieContainer |
CookieContainer |
Gets or sets the container for cookies that are sent with requests. |
Credentials |
ICredentials |
Gets or sets the credentials used for basic authentication. |
MaxAutomaticRedirections |
int |
Gets or sets the maximum number of automatic redirections. Default is 50. |
Proxy |
IWebProxy |
Gets or sets the proxy used to send requests. |
UseCookies |
bool |
Gets or sets a value that indicates whether the handler uses cookies. Default is true. |
UseProxy |
bool |
Gets or sets a value that indicates whether the handler uses the proxy. Default is true. |
| Signature | Description |
|---|---|
SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
Sends an HTTP request to the specified host and gets the response headers and status code.
Parameters:
|
Dispose() |
Releases the unmanaged resources used by the HttpClientHandler and optionally releases the managed resources. |
The HttpClientHandler is typically used to customize the behavior of an HttpClient instance.
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public static async Task Main(string[] args)
{
// Create an HttpClientHandler instance
var handler = new HttpClientHandler
{
// Configure custom behavior
UseCookies = true,
CookieContainer = new CookieContainer(),
AllowAutoRedirect = true,
MaxAutomaticRedirections = 10,
Proxy = new WebProxy("http://myproxy.com:8080")
};
// Create an HttpClient instance with the custom handler
using (HttpClient client = new HttpClient(handler))
{
try
{
HttpResponseMessage response = await client.GetAsync("https://www.example.com");
response.EnsureSuccessStatusCode(); // Throws if HTTP status code is an error
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody.Substring(0, 200) + "..."); // Print first 200 chars
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}