HttpClient HttpClient HttpClient HttpClient Class

定义

提供基本类,用于发送 HTTP 请求和接收来自通过 URI 确认的资源的 HTTP 响应。Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

public ref class HttpClient : System::Net::Http::HttpMessageInvoker
public class HttpClient : System.Net.Http.HttpMessageInvoker
type HttpClient = class
    inherit HttpMessageInvoker
Public Class HttpClient
Inherits HttpMessageInvoker
继承

示例

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
 
static async Task Main()
{
  // 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();
     // Above three lines can be replaced with new helper method below
     // string responseBody = await client.GetStringAsync(uri);

     Console.WriteLine(responseBody);
  }  
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");	
     Console.WriteLine("Message :{0} ",e.Message);
  }
}
' HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
   Shared ReadOnly client As HttpClient = New HttpClient()

Private Shared Async Function Main() As Task
	' Call asynchronous network methods in a try/catch block to handle exceptions.
	Try
		Dim response As HttpResponseMessage = Await client.GetAsync("http://www.contoso.com/")
		response.EnsureSuccessStatusCode()
		Dim responseBody As String = Await response.Content.ReadAsStringAsync()
		' Above three lines can be replaced with new helper method below
		' Dim responseBody As String = Await client.GetStringAsync(uri)

		Console.WriteLine(responseBody)
	Catch e As HttpRequestException
		Console.WriteLine(Environment.NewLine & "Exception Caught!")
		Console.WriteLine("Message :{0} ", e.Message)
	End Try
End Function

前面的代码示例使用async Task Main()入口点。The preceding code example uses an async Task Main() entry point. 该功能需要C# 7.1 或更高版本。That feature requires C# 7.1 or later.

注解

HttpClient类实例充当发送 HTTP 请求的会话。The HttpClient class instance acts as a session to send HTTP requests. HttpClient实例是对该实例执行的所有请求应用的设置的集合。An HttpClient instance is a collection of settings applied to all requests executed by that instance. 此外, 每个HttpClient实例都使用其自己的连接池, 并从其他HttpClient实例所执行的请求隔离其请求。In addition, every HttpClient instance uses its own connection pool, isolating its requests from requests executed by other HttpClient instances.

HttpClient还可用作更具体的 HTTP 客户端的基类。The HttpClient also acts as a base class for more specific HTTP clients. 例如, FacebookHttpClient 提供特定于 Facebook web 服务的其他方法 (例如, GetFriends 方法)。An example would be a FacebookHttpClient providing additional methods specific to a Facebook web service (a GetFriends method, for instance). 派生类不应重写类的虚方法。Derived classes should not override the virtual methods on the class. 而应使用接受HttpMessageHandler的构造函数重载来配置任何预处理或后请求处理。Instead, use a constructor overload that accepts HttpMessageHandler to configure any pre- or post-request processing instead.

默认情况下, 在 .NET Framework 和HttpWebRequest Mono 上, 用于将请求发送到服务器。By default on .NET Framework and Mono, HttpWebRequest is used to send requests to the server. 可以通过在采用HttpMessageHandler实例作为参数的构造函数重载之一中指定不同的通道来修改此行为。This behavior can be modified by specifying a different channel in one of the constructor overloads taking a HttpMessageHandler instance as parameter. 如果需要使用身份验证或缓存等功能WebRequestHandler , 可使用来配置设置, 并将实例传递给构造函数。If features like authentication or caching are required, WebRequestHandler can be used to configure settings and the instance can be passed to the constructor. 返回的处理程序可传递给采用HttpMessageHandler参数的构造函数重载之一。The returned handler can be passed to one of the constructor overloads taking a HttpMessageHandler parameter.

如果System.Net.Http命名空间中HttpClient使用和相关类的应用打算下载大量数据 (50 mb 或更多), 则应用应流式传输这些下载内容, 而不使用默认缓冲。If an app using HttpClient and related classes in the System.Net.Http namespace intends to download large amounts of data (50 megabytes or more), then the app should stream those downloads and not use the default buffering. 如果使用默认缓冲, 则客户端内存使用量将会非常大, 这可能会显著降低性能。If the default buffering is used the client memory usage will get very large, potentially resulting in substantially reduced performance.

以下方法是线程安全的:The following methods are thread safe:

  1. CancelPendingRequests

  2. DeleteAsync

  3. GetAsync

  4. GetByteArrayAsync

  5. GetStreamAsync

  6. GetStringAsync

  7. PostAsync

  8. PutAsync

  9. SendAsync

HttpClient用于在应用程序的整个生存期内实例化一次并重复使用。HttpClient is intended to be instantiated once and re-used throughout the life of an application. 实例化每个请求的 HttpClient 类将耗尽重负载下可用的插槽数。Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 这将导致 SocketException 错误。This will result in SocketException errors. 下面是正确使用 HttpClient 的示例。Below is an example using HttpClient correctly.

public class GoodController : ApiController
{
    private static readonly HttpClient HttpClient;

    static GoodController()
    {
        HttpClient = new HttpClient();
    }
}
  Public Class GoodController
    Inherits ApiController  

    Private Shared ReadOnly HttpClient As HttpClient  

    Shared Sub New()  
        HttpClient = New HttpClient()
    End Sub
End Class

HttpClient是一个高级 API, 用于包装其运行的每个平台上可用的较低级别功能。The HttpClient is a high-level API that wraps the lower-level functionality available on each platform where it runs.

在每个平台HttpClient上, 尝试使用最佳的可用传输:On each platform, HttpClient tries to use the best available transport:

主机/运行时Host/Runtime Backend
Windows/.NET FrameworkWindows/.NET Framework HttpWebRequest
Windows/MonoWindows/Mono HttpWebRequest
Windows/UWPWindows/UWP Windows native WinHttpHandler (支持 HTTP 2.0)Windows native WinHttpHandler (HTTP 2.0 capable)
Windows/.NET Core 1.0-2。0Windows/.NET Core 1.0-2.0 Windows native WinHttpHandler (支持 HTTP 2.0)Windows native WinHttpHandler (HTTP 2.0 capable)
Android/XamarinAndroid/Xamarin 在生成时选择。Selected at build-time. 可以使用HttpWebRequest或配置为使用 Android 的本机HttpURLConnectionCan either use HttpWebRequest or be configured to use Android's native HttpURLConnection
iOS、tvOS、watchOS/XamariniOS, tvOS, watchOS/Xamarin 在生成时选择。Selected at build-time. 可以使用HttpWebRequest或配置为使用 Apple 的NSUrlSession (支持 HTTP 2.0)Can either use HttpWebRequest or be configured to use Apple's NSUrlSession (HTTP 2.0 capable)
macOS/XamarinmacOS/Xamarin 在生成时选择。Selected at build-time. 可以使用HttpWebRequest或配置为使用 Apple 的NSUrlSession (支持 HTTP 2.0)Can either use HttpWebRequest or be configured to use Apple's NSUrlSession (HTTP 2.0 capable)
macOS/MonomacOS/Mono HttpWebRequest
macOS/.NET Core 1.0-2。0macOS/.NET Core 1.0-2.0 libcurl基于的 HTTP 传输 (支持 HTTP 2.0)libcurl-based HTTP transport (HTTP 2.0 capable)
Linux/MonoLinux/Mono HttpWebRequest
Linux/.NET Core 1.0-2。0Linux/.NET Core 1.0-2.0 libcurl基于的 HTTP 传输 (支持 HTTP 2.0)libcurl-based HTTP transport (HTTP 2.0 capable)
.NET Core 2.1 及更高版本.NET Core 2.1 and later System.Net.Http.SocketsHttpHandler

用户还可以通过HttpClient HttpClient调用采用HttpMessageHandler的构造函数, 为配置特定传输。Users can also configure a specific transport for HttpClient by invoking the HttpClient constructor that takes an HttpMessageHandler.

HttpClient 和 .NET CoreHttpClient and .NET Core

从 .net Core 2.1 开始, System.Net.Http.SocketsHttpHandlerHttpClientHandler而不是提供由较高级别的 HTTP 网络类 (如) HttpClient使用的实现。Starting with .NET Core 2.1, the System.Net.Http.SocketsHttpHandler class instead of HttpClientHandler provides the implementation used by higher-level HTTP networking classes such as HttpClient. 使用SocketsHttpHandler可提供多种优势:The use of SocketsHttpHandler offers a number of advantages:

  • 对照以前的实现,可以看到显著的性能改进。A significant performance improvement when compared with the previous implementation.

  • 消除了平台依赖项, 从而简化了部署和服务。The elimination of platform dependencies, which simplifies deployment and servicing. 例如, libcurl不再依赖于适用于 macOS 的 .net core 和适用于 Linux 的 .net core。For example, libcurl is no longer a dependency on .NET Core for macOS and .NET Core for Linux.

  • 各种 .NET 平台的行为一致。Consistent behavior across all .NET platforms.

如果不需要此更改, 可以通过多种方式将应用程序配置为System.Net.Http.HttpClientHandler使用旧版本:If this change is undesirable, you can configure your application to use the older System.Net.Http.HttpClientHandler instead in a number of ways:

  • 通过调用AppContext.SetSwitch方法, 如下所示:By calling the AppContext.SetSwitch method as follows:

    AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
    
    AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", False)
    
  • 通过在System.Net.Http.UseSocketsHttpHandler . runtimeconfig.template.json配置文件中定义开关 netcore:By defining the System.Net.Http.UseSocketsHttpHandler switch in the .netcore.runtimeconfig.json configuration file:

    "runtimeOptions": {
      "configProperties": {
          "System.Net.Http.UseSocketsHttpHandler": false
      }
    }
    
  • 通过定义名为DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER的环境变量并将其设置false为或0。By defining an environment variable named DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER and setting it to either false or 0.

构造函数

HttpClient() HttpClient() HttpClient() HttpClient()

使用释放此实例时释放的 HttpClientHandler 初始化 HttpClient 类的新实例。Initializes a new instance of the HttpClient class using a HttpClientHandler that is disposed when this instance is disposed.

HttpClient(HttpMessageHandler) HttpClient(HttpMessageHandler) HttpClient(HttpMessageHandler) HttpClient(HttpMessageHandler)

使用指定的处理程序初始化 HttpClient 类的新实例。Initializes a new instance of the HttpClient class with the specified handler. 处理程序在释放此实例时被释放。The handler is disposed when this instance is disposed.

HttpClient(HttpMessageHandler, Boolean) HttpClient(HttpMessageHandler, Boolean) HttpClient(HttpMessageHandler, Boolean) HttpClient(HttpMessageHandler, Boolean)

使用提供的处理程序初始化 HttpClient 类的新实例,并指定在释放此实例时是否应释放该处理程序。Initializes a new instance of the HttpClient class with the provided handler, and specifies whether that handler should be disposed when this instance is disposed.

属性

BaseAddress BaseAddress BaseAddress BaseAddress

获取或设置发送请求时使用的 Internet 资源的统一资源标识符 (URI) 的基址。Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.

DefaultProxy DefaultProxy DefaultProxy DefaultProxy

获取或设置全局 HTTP 代理。Gets or sets the global Http proxy.

DefaultRequestHeaders DefaultRequestHeaders DefaultRequestHeaders DefaultRequestHeaders

获取与每个请求一起发送的标题。Gets the headers which should be sent with each request.

DefaultRequestVersion DefaultRequestVersion DefaultRequestVersion DefaultRequestVersion

获取或设置对此 HttpClient 实例发出的后续请求使用的默认 HTTP 版本。Gets or sets the default HTTP version used on subsequent requests made by this HttpClient instance.

MaxResponseContentBufferSize MaxResponseContentBufferSize MaxResponseContentBufferSize MaxResponseContentBufferSize

获取或设置读取响应内容时要缓冲的最大字节数。Gets or sets the maximum number of bytes to buffer when reading the response content.

Timeout Timeout Timeout Timeout

获取或设置请求超时前等待的时间跨度。Gets or sets the timespan to wait before the request times out.

方法

CancelPendingRequests() CancelPendingRequests() CancelPendingRequests() CancelPendingRequests()

取消该实例所有挂起的请求。Cancel all pending requests on this instance.

DeleteAsync(String) DeleteAsync(String) DeleteAsync(String) DeleteAsync(String)

以异步操作将 DELETE 请求发送给指定 URI。Send a DELETE request to the specified Uri as an asynchronous operation.

DeleteAsync(String, CancellationToken) DeleteAsync(String, CancellationToken) DeleteAsync(String, CancellationToken) DeleteAsync(String, CancellationToken)

用以异步操作的取消标记发送 DELETE 请求到指定的 URI。Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.

DeleteAsync(Uri) DeleteAsync(Uri) DeleteAsync(Uri) DeleteAsync(Uri)

以异步操作将 DELETE 请求发送给指定 URI。Send a DELETE request to the specified Uri as an asynchronous operation.

DeleteAsync(Uri, CancellationToken) DeleteAsync(Uri, CancellationToken) DeleteAsync(Uri, CancellationToken) DeleteAsync(Uri, CancellationToken)

用以异步操作的取消标记发送 DELETE 请求到指定的 URI。Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.

Dispose() Dispose() Dispose() Dispose()

释放由 HttpMessageInvoker 使用的非托管资源和托管资源。Releases the unmanaged resources and disposes of the managed resources used by the HttpMessageInvoker.

(Inherited from HttpMessageInvoker)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由 HttpClient 使用的非托管资源,并可根据需要释放托管资源。Releases the unmanaged resources used by the HttpClient and optionally disposes of the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetAsync(String) GetAsync(String) GetAsync(String) GetAsync(String)

以异步操作将 GET 请求发送给指定 URI。Send a GET request to the specified Uri as an asynchronous operation.

GetAsync(String, CancellationToken) GetAsync(String, CancellationToken) GetAsync(String, CancellationToken) GetAsync(String, CancellationToken)

用以异步操作的取消标记发送 GET 请求到指定的 URI。Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.

GetAsync(String, HttpCompletionOption) GetAsync(String, HttpCompletionOption) GetAsync(String, HttpCompletionOption) GetAsync(String, HttpCompletionOption)

用以异步操作的 HTTP 完成选项发送 GET 请求到指定的 URI。Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation.

GetAsync(String, HttpCompletionOption, CancellationToken) GetAsync(String, HttpCompletionOption, CancellationToken) GetAsync(String, HttpCompletionOption, CancellationToken) GetAsync(String, HttpCompletionOption, CancellationToken)

用以异步操作的 HTTP 完成选项和取消标记发送 GET 请求到指定的 URI。Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation.

GetAsync(Uri) GetAsync(Uri) GetAsync(Uri) GetAsync(Uri)

以异步操作将 GET 请求发送给指定 URI。Send a GET request to the specified Uri as an asynchronous operation.

GetAsync(Uri, CancellationToken) GetAsync(Uri, CancellationToken) GetAsync(Uri, CancellationToken) GetAsync(Uri, CancellationToken)

用以异步操作的取消标记发送 GET 请求到指定的 URI。Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.

GetAsync(Uri, HttpCompletionOption) GetAsync(Uri, HttpCompletionOption) GetAsync(Uri, HttpCompletionOption) GetAsync(Uri, HttpCompletionOption)

用以异步操作的 HTTP 完成选项发送 GET 请求到指定的 URI。Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation.

GetAsync(Uri, HttpCompletionOption, CancellationToken) GetAsync(Uri, HttpCompletionOption, CancellationToken) GetAsync(Uri, HttpCompletionOption, CancellationToken) GetAsync(Uri, HttpCompletionOption, CancellationToken)

用以异步操作的 HTTP 完成选项和取消标记发送 GET 请求到指定的 URI。Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation.

GetByteArrayAsync(String) GetByteArrayAsync(String) GetByteArrayAsync(String) GetByteArrayAsync(String)

将 GET 请求发送到指定 URI 并在异步操作中以字节数组的形式返回响应正文。Sends a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.

GetByteArrayAsync(Uri) GetByteArrayAsync(Uri) GetByteArrayAsync(Uri) GetByteArrayAsync(Uri)

将 GET 请求发送到指定 URI 并在异步操作中以字节数组的形式返回响应正文。Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetStreamAsync(String) GetStreamAsync(String) GetStreamAsync(String) GetStreamAsync(String)

将 GET 请求发送到指定 URI 并在异步操作中以流的形式返回响应正文。Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.

GetStreamAsync(Uri) GetStreamAsync(Uri) GetStreamAsync(Uri) GetStreamAsync(Uri)

将 GET 请求发送到指定 URI 并在异步操作中以流的形式返回响应正文。Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.

GetStringAsync(String) GetStringAsync(String) GetStringAsync(String) GetStringAsync(String)

将 GET 请求发送到指定 URI 并在异步操作中以字符串的形式返回响应正文。Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.

GetStringAsync(Uri) GetStringAsync(Uri) GetStringAsync(Uri) GetStringAsync(Uri)

将 GET 请求发送到指定 URI 并在异步操作中以字符串的形式返回响应正文。Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.

GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
PatchAsync(String, HttpContent) PatchAsync(String, HttpContent) PatchAsync(String, HttpContent) PatchAsync(String, HttpContent)

以异步操作方式将 PATCH 请求发送到指定为字符串的 URI。Sends a PATCH request to a Uri designated as a string as an asynchronous operation.

PatchAsync(String, HttpContent, CancellationToken) PatchAsync(String, HttpContent, CancellationToken) PatchAsync(String, HttpContent, CancellationToken) PatchAsync(String, HttpContent, CancellationToken)

以异步操作方式将带有取消令牌的 PATCH 请求发送到表示为字符串的 URI。Sends a PATCH request with a cancellation token to a Uri represented as a string as an asynchronous operation.

PatchAsync(Uri, HttpContent) PatchAsync(Uri, HttpContent) PatchAsync(Uri, HttpContent) PatchAsync(Uri, HttpContent)

以异步操作方式发送 PATCH 请求。Sends a PATCH request as an asynchronous operation.

PatchAsync(Uri, HttpContent, CancellationToken) PatchAsync(Uri, HttpContent, CancellationToken) PatchAsync(Uri, HttpContent, CancellationToken) PatchAsync(Uri, HttpContent, CancellationToken)

以异步操作方式发送带有取消令牌的 PATCH 请求。Sends a PATCH request with a cancellation token as an asynchronous operation.

PostAsync(String, HttpContent) PostAsync(String, HttpContent) PostAsync(String, HttpContent) PostAsync(String, HttpContent)

以异步操作将 POST 请求发送给指定 URI。Send a POST request to the specified Uri as an asynchronous operation.

PostAsync(String, HttpContent, CancellationToken) PostAsync(String, HttpContent, CancellationToken) PostAsync(String, HttpContent, CancellationToken) PostAsync(String, HttpContent, CancellationToken)

用以异步操作的取消标记发送 POST 请求。Send a POST request with a cancellation token as an asynchronous operation.

PostAsync(Uri, HttpContent) PostAsync(Uri, HttpContent) PostAsync(Uri, HttpContent) PostAsync(Uri, HttpContent)

以异步操作将 POST 请求发送给指定 URI。Send a POST request to the specified Uri as an asynchronous operation.

PostAsync(Uri, HttpContent, CancellationToken) PostAsync(Uri, HttpContent, CancellationToken) PostAsync(Uri, HttpContent, CancellationToken) PostAsync(Uri, HttpContent, CancellationToken)

用以异步操作的取消标记发送 POST 请求。Send a POST request with a cancellation token as an asynchronous operation.

PutAsync(String, HttpContent) PutAsync(String, HttpContent) PutAsync(String, HttpContent) PutAsync(String, HttpContent)

以异步操作将 PUT 请求发送给指定 URI。Send a PUT request to the specified Uri as an asynchronous operation.

PutAsync(String, HttpContent, CancellationToken) PutAsync(String, HttpContent, CancellationToken) PutAsync(String, HttpContent, CancellationToken) PutAsync(String, HttpContent, CancellationToken)

用以异步操作的取消标记发送 PUT 请求。Send a PUT request with a cancellation token as an asynchronous operation.

PutAsync(Uri, HttpContent) PutAsync(Uri, HttpContent) PutAsync(Uri, HttpContent) PutAsync(Uri, HttpContent)

以异步操作将 PUT 请求发送给指定 URI。Send a PUT request to the specified Uri as an asynchronous operation.

PutAsync(Uri, HttpContent, CancellationToken) PutAsync(Uri, HttpContent, CancellationToken) PutAsync(Uri, HttpContent, CancellationToken) PutAsync(Uri, HttpContent, CancellationToken)

用以异步操作的取消标记发送 PUT 请求。Send a PUT request with a cancellation token as an asynchronous operation.

SendAsync(HttpRequestMessage) SendAsync(HttpRequestMessage) SendAsync(HttpRequestMessage) SendAsync(HttpRequestMessage)

以异步操作发送 HTTP 请求。Send an HTTP request as an asynchronous operation.

SendAsync(HttpRequestMessage, CancellationToken) SendAsync(HttpRequestMessage, CancellationToken) SendAsync(HttpRequestMessage, CancellationToken) SendAsync(HttpRequestMessage, CancellationToken)

以异步操作发送 HTTP 请求。Send an HTTP request as an asynchronous operation.

SendAsync(HttpRequestMessage, HttpCompletionOption) SendAsync(HttpRequestMessage, HttpCompletionOption) SendAsync(HttpRequestMessage, HttpCompletionOption) SendAsync(HttpRequestMessage, HttpCompletionOption)

以异步操作发送 HTTP 请求。Send an HTTP request as an asynchronous operation.

SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken) SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken) SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken) SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken)

以异步操作发送 HTTP 请求。Send an HTTP request as an asynchronous operation.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

适用于

另请参阅