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
继承

示例

static async Task Main()
{
   // Create a New HttpClient object and dispose it when done, so the app doesn't leak resources
   using (HttpClient client = new HttpClient())
   {
      // 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);
      }
   }
}

前面的代码示例使用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. 例如,就会提供特定于 Facebook web 服务的附加方法 FacebookHttpClient (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 和 MonoHttpWebRequest用于将请求发送到服务器。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.

如果应用程序使用HttpClient中的相关类和System.Net.Http命名空间打算下载大量数据 (50 兆字节或多个),则该应用程序应流式传输这些下载并使用默认缓冲。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
{
    // OK
    private static readonly HttpClient HttpClient;

    static GoodController()
    {
        HttpClient = new HttpClient();
    }
}

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 本机WinHttpHandler(支持 HTTP 2.0)Windows native WinHttpHandler (HTTP 2.0 capable)
Windows/.NET CoreWindows/.NET Core Windows 本机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 CoremacOS/.NET Core libcurl-基于 HTTP 传输协议 (HTTP 2.0 支持)libcurl-based HTTP transport (HTTP 2.0 capable)
Linux/MonoLinux/Mono HttpWebRequest
Linux/.NET CoreLinux/.NET Core libcurl-基于 HTTP 传输协议 (HTTP 2.0 支持)libcurl-based HTTP transport (HTTP 2.0 capable)

用户还可以配置的特定传输HttpClient通过调用HttpClient构造函数采用HttpMessageHandlerUsers 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.1System.Net.Http.SocketsHttpHandler类而不是HttpClientHandler提供实现由更高级别的 HTTP 网络类如HttpClientStarting 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. 可以配置应用程序以使用较旧System.Net.Http.HttpClientHandler改为通过调用SetSwitch方法,如下所示:You can configure your application to use the older System.Net.Http.HttpClientHandler instead by calling the SetSwitch method as follows:

AppContext.SetSwitch("System.Net.Http.useSocketsHttpHandler", false);
AppContext.SetSwitch("System.Net.Http.useSocketsHttpHandler", False)

构造函数

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

初始化 HttpClient 类的新实例。Initializes a new instance of the HttpClient class.

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

用特定的处理程序初始化 HttpClient 类的新实例。Initializes a new instance of the HttpClient class with a specific handler.

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

用特定的处理程序初始化 HttpClient 类的新实例。Initializes a new instance of the HttpClient class with a specific handler.

属性

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.

DefaultRequestHeaders DefaultRequestHeaders DefaultRequestHeaders DefaultRequestHeaders

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

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)
PatchAsync(String, HttpContent, CancellationToken) PatchAsync(String, HttpContent, CancellationToken) PatchAsync(String, HttpContent, CancellationToken) PatchAsync(String, HttpContent, CancellationToken)
PatchAsync(Uri, HttpContent) PatchAsync(Uri, HttpContent) PatchAsync(Uri, HttpContent) PatchAsync(Uri, HttpContent)
PatchAsync(Uri, HttpContent, CancellationToken) PatchAsync(Uri, HttpContent, CancellationToken) PatchAsync(Uri, HttpContent, CancellationToken) PatchAsync(Uri, HttpContent, CancellationToken)
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)

适用于

另请参阅