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 和 Mono 上HttpWebRequest用來將要求傳送至伺服器。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 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
{
    // 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 Core 1.0-2.0Windows/.NET Core 1.0-2.0 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 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建構函式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.1 中,從開始System.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. 使用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 的相依性 .NET Core for Linux。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切換移入 。 netcore.runtimeconfig.json組態檔: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()

初始化 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

取得或設定傳送要求時所使用之網際網路資源的統一資源識別元 (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()

釋放 Unmanaged 資源,並處置 HttpMessageInvoker 所使用的 Managed 資源。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 所使用的 Unmanaged 資源,並選擇性處置 Managed 資源。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)

以非同步作業的方式,傳送 GET 要求和 HTTP 完成選項至指定的 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)

以非同步作業的方式,傳送 GET 要求和 HTTP 完成選項以及取消語彙基元至指定的 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)

以非同步作業的方式,傳送 GET 要求和 HTTP 完成選項至指定的 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)

以非同步作業的方式,傳送 GET 要求和 HTTP 完成選項以及取消語彙基元至指定的 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 的淺層複本 (Shallow Copy)。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)

適用於

另請參閱