HttpClientHandler Classe

Definição

O manipulador de mensagens padrão usado pelo HttpClient no .NET Framework e .NET Core 2.0 e versões anteriores.The default message handler used by HttpClient in .NET Framework and .NET Core 2.0 and earlier.

public ref class HttpClientHandler : System::Net::Http::HttpMessageHandler
public class HttpClientHandler : System.Net.Http.HttpMessageHandler
type HttpClientHandler = class
    inherit HttpMessageHandler
Public Class HttpClientHandler
Inherits HttpMessageHandler
Herança
HttpClientHandler
Derivado

Exemplos

static async Task Main()
{
   // Create an HttpClientHandler object and set to use default credentials
   HttpClientHandler handler = new HttpClientHandler();
   handler.UseDefaultCredentials = true;

   // Create an HttpClient object
   HttpClient client = new HttpClient(handler);

   // Call asynchronous network methods in a try/catch block to handle exceptions
   try
   {
      HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");

      response.EnsureSuccessStatusCode();

      string responseBody = await response.Content.ReadAsStringAsync();
      Console.WriteLine(responseBody);
   }
   catch(HttpRequestException e)
   {
       Console.WriteLine("\nException Caught!");
       Console.WriteLine("Message :{0} ",e.Message);
   }

   // Need to call dispose on the HttpClient and HttpClientHandler objects
   // when done using them, so the app doesn't leak resources
   handler.Dispose();
   client.Dispose();
}

O exemplo de código anterior usa um async Task Main() ponto de entrada.The preceding code example uses an async Task Main() entry point. Esse recurso requer C# 7,1 ou posterior.That feature requires C# 7.1 or later.

Comentários

A HttpClientHandler classe e as classes derivadas de ti permitem que os desenvolvedores configurem uma variedade de opções que variam de proxies a autenticação.The HttpClientHandler class and classes derived from it enable developers to configure a variety of options ranging from proxies to authentication.

HttpClientHandler no .NET CoreHttpClientHandler in .NET Core

A partir do .NET Core 2,1, a implementação da HttpClientHandler classe foi alterada para ser baseada na pilha de protocolos http de plataforma cruzada usada pela System.Net.Http.SocketsHttpHandler classe.Starting in .NET Core 2.1, the implementation of the HttpClientHandler class was changed to be based on the cross-platform HTTP protocol stack used by the System.Net.Http.SocketsHttpHandler class. Antes do .NET Core 2,1, a HttpClientHandler classe usava pilhas de protocolo http mais antigas ( WinHttpHandler no Windows e CurlHandler uma classe interna implementada sobre o componente libcurl nativo do Linux, no Linux).Prior to .NET Core 2.1, the HttpClientHandler class used older HTTP protocol stacks (WinHttpHandler on Windows and CurlHandler, an internal class implemented on top of Linux's native libcurl component, on Linux).

Você pode configurar seu aplicativo para usar as pilhas de protocolo HTTP mais antigas de uma das três maneiras a seguir:You can configure your app to use the older HTTP protocol stacks in one of the following three ways:

  • Chame o AppContext.SetSwitch método:Call the AppContext.SetSwitch method:

    AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
    
    AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", False)
    
  • Defina a System.Net.Http.UseSocketsHttpHandler opção na .netcore.runtimeconfig.jsno arquivo de configuração:Define the System.Net.Http.UseSocketsHttpHandler switch in the .netcore.runtimeconfig.json configuration file:

    "runtimeOptions": {
      "configProperties": {
          "System.Net.Http.UseSocketsHttpHandler": false
      }
    }
    
  • Defina uma variável de ambiente chamada DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER e defina-a como false or 0.Define an environment variable named DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER and set it to either false or 0.

Construtores

HttpClientHandler()

Cria uma instância de uma classe HttpClientHandler.Creates an instance of a HttpClientHandler class.

Propriedades

AllowAutoRedirect

Obtém ou define um valor que indica se o manipulador deve seguir as respostas de redirecionamento.Gets or sets a value that indicates whether the handler should follow redirection responses.

AutomaticDecompression

Obtém ou define o tipo de método de descompactação usado pelo manipulador para descompactação automática da resposta de conteúdo HTTP.Gets or sets the type of decompression method used by the handler for automatic decompression of the HTTP content response.

CheckCertificateRevocationList

Obtém ou define um valor que indica se o certificado é verificado em relação à lista de revogação de autoridade de certificação.Gets or sets a value that indicates whether the certificate is checked against the certificate authority revocation list.

ClientCertificateOptions

Obtém ou define um valor que indica se o certificado é selecionado automaticamente do repositório de certificados ou se o chamador tem permissão para passar um certificado do cliente específico.Gets or sets a value that indicates if the certificate is automatically picked from the certificate store or if the caller is allowed to pass in a specific client certificate.

ClientCertificates

Obtém a coleção de certificados de segurança que estão associadas a solicitações ao servidor.Gets the collection of security certificates that are associated requests to the server.

CookieContainer

Obtém ou define o contêiner de cookies usado para armazenar cookies de servidor pelo manipulador.Gets or sets the cookie container used to store server cookies by the handler.

Credentials

Obtém ou define informações de autenticação usadas por este manipulador.Gets or sets authentication information used by this handler.

DangerousAcceptAnyServerCertificateValidator

Obtém um delegado em cache que sempre retorna true.Gets a cached delegate that always returns true.

DefaultProxyCredentials

Quando o proxy padrão (sistema) está sendo usado, obtém ou define as credenciais a serem enviadas ao servidor proxy padrão para autenticação.When the default (system) proxy is being used, gets or sets the credentials to submit to the default proxy server for authentication. O proxy padrão é usado apenas quando UseProxy é definido como true e Proxy é definido como null.The default proxy is used only when UseProxy is set to true and Proxy is set to null.

MaxAutomaticRedirections

Obtém ou define o número máximo de redirecionamentos que o manipulador segue.Gets or sets the maximum number of redirects that the handler follows.

MaxConnectionsPerServer

Obtém ou define o número máximo de conexões simultâneas (por ponto de extremidade do servidor) permitidas ao fazer solicitações usando um objeto HttpClient.Gets or sets the maximum number of concurrent connections (per server endpoint) allowed when making requests using an HttpClient object. Observe que o limite é por ponto de extremidade do servidor, portanto, por exemplo, um valor de 256 permitiria 256 conexões simultâneas com http://www.adatum.com/ e outras 256 com http://www.adventure-works.com/.Note that the limit is per server endpoint, so for example a value of 256 would permit 256 concurrent connections to http://www.adatum.com/ and another 256 to http://www.adventure-works.com/.

MaxRequestContentBufferSize

Obtém ou define o tamanho máximo do buffer de conteúdo de solicitação usado pelo manipulador.Gets or sets the maximum request content buffer size used by the handler.

MaxResponseHeadersLength

Obtém ou define o comprimento máximo, em quilobytes (1024 bytes), dos cabeçalhos de resposta.Gets or sets the maximum length, in kilobytes (1024 bytes), of the response headers. Por exemplo, se o valor é 64, 65.536 bytes são permitidos para o comprimento máximo dos cabeçalhos de resposta.For example, if the value is 64, then 65536 bytes are allowed for the maximum response headers' length.

PreAuthenticate

Obtém ou define um valor que indica se o manipulador envia um cabeçalho de autorização com a solicitação.Gets or sets a value that indicates whether the handler sends an Authorization header with the request.

Properties

Obtém um dicionário gravável (ou seja, um mapa) de propriedades personalizadas para as solicitações de HttpClient.Gets a writable dictionary (that is, a map) of custom properties for the HttpClient requests. O dicionário é inicializado vazio. Você pode inserir e consultar pares chave-valor para seus manipuladores personalizados e processamento especial.The dictionary is initialized empty; you can insert and query key-value pairs for your custom handlers and special processing.

Proxy

Obtém ou define as informações de proxy usadas pelo manipulador.Gets or sets proxy information used by the handler.

ServerCertificateCustomValidationCallback

Obtém ou define um método de retorno de chamada para validar o certificado do servidor.Gets or sets a callback method to validate the server certificate.

SslProtocols

Obtém ou define o protocolo TLS/SSL usado pelos objetos HttpClient gerenciados pelo objeto HttpClientHandler.Gets or sets the TLS/SSL protocol used by the HttpClient objects managed by the HttpClientHandler object.

SupportsAutomaticDecompression

Obtém um valor que indica se o manipulador dá suporte a descompactação de conteúdo de resposta automática.Gets a value that indicates whether the handler supports automatic response content decompression.

SupportsProxy

Obtém um valor que indica se o manipulador dá suporte a configurações de proxy.Gets a value that indicates whether the handler supports proxy settings.

SupportsRedirectConfiguration

Obtém um valor que indica se o manipulador dá ou não suporte a definições de configuração para as propriedades AllowAutoRedirect e MaxAutomaticRedirections.Gets a value that indicates whether the handler supports configuration settings for the AllowAutoRedirect and MaxAutomaticRedirections properties.

UseCookies

Obtém ou define um valor que indica se o manipulador utiliza a propriedade CookieContainer para armazenar cookies de servidor e usa esses cookies ao enviar solicitações.Gets or sets a value that indicates whether the handler uses the CookieContainer property to store server cookies and uses these cookies when sending requests.

UseDefaultCredentials

Obtém ou define um valor que controla se as credenciais padrão são enviadas com solicitações pelo manipulador.Gets or sets a value that controls whether default credentials are sent with requests by the handler.

UseProxy

Obtém ou define um valor que indica se o manipulador usa um proxy para solicitações.Gets or sets a value that indicates whether the handler uses a proxy for requests.

Métodos

Dispose()

Libera os recursos não gerenciados e descarta aqueles gerenciados usados pelo HttpMessageHandler.Releases the unmanaged resources and disposes of the managed resources used by the HttpMessageHandler.

(Herdado de HttpMessageHandler)
Dispose(Boolean)

Libera os recursos não gerenciados usados pelo HttpClientHandler e, opcionalmente, descarta os recursos gerenciados.Releases the unmanaged resources used by the HttpClientHandler and optionally disposes of the managed resources.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
Send(HttpRequestMessage, CancellationToken)

Cria uma instância de HttpResponseMessage com base nas informações fornecidas no HttpRequestMessage.Creates an instance of HttpResponseMessage based on the information provided in the HttpRequestMessage.

Send(HttpRequestMessage, CancellationToken)

Quando substituído em uma classe derivada, envia uma solicitação HTTP com a solicitação e o token de cancelamento especificados.When overridden in a derived class, sends an HTTP request with the specified request and cancellation token. Caso contrário, gerará um NotSupportedException.Otherwise, throws a NotSupportedException.

(Herdado de HttpMessageHandler)
SendAsync(HttpRequestMessage, CancellationToken)

Cria uma instância de HttpResponseMessage com base nas informações fornecidas no HttpRequestMessage como uma operação que não será bloqueada.Creates an instance of HttpResponseMessage based on the information provided in the HttpRequestMessage as an operation that will not block.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Aplica-se a