HttpClient 類別

定義

提供基底類別,用於傳送 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. 例如,提供 Facebook web 服務特有的其他方法(例如,GetFriends 方法)的 FacebookHttpClient。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.

如果在 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

使用者也可以藉由叫用接受 HttpMessageHandlerHttpClient 函式,來設定 HttpClient 的特定傳輸。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.SocketsHttpHandler 類別,而不是 HttpClientHandler 提供較高階 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)
    
  • 藉由定義netcore. .runtimeconfig.json. json設定檔中的 System.Net.Http.UseSocketsHttpHandler 參數: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 來初始化 HttpClientHandler 類別的新執行個體。Initializes a new instance of the HttpClient class using a HttpClientHandler that is disposed when this instance is disposed.

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 類別的新執行個體,並指定當處置此執行個體時是否應該處置該處理常式。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

取得或設定網際網路在傳送要求時使用的統一資源識別項 (URI) 基礎位址。Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.

DefaultProxy

取得或設定全域 HTTP Proxy。Gets or sets the global Http proxy.

DefaultRequestHeaders

取得應該與每個要求一併傳送的處理常方式。Gets the headers which should be sent with each request.

DefaultRequestVersion

取得或設定用於這個 HttpClient 執行個體所提出後續要求的預設 HTTP 版本。Gets or sets the default HTTP version used on subsequent requests made by this HttpClient instance.

MaxResponseContentBufferSize

取得或設定由於讀取回應內容時緩衝的最大位元組數。Gets or sets the maximum number of bytes to buffer when reading the response content.

Timeout

取得或設定要求逾時前等候的時間長度。Gets or sets the timespan to wait before the request times out.

方法

CancelPendingRequests()

取消此執行個體上的所有擱置要求。Cancel all pending requests on this instance.

DeleteAsync(String)

以非同步作業的方式,將 DELETE 要求傳送至指定的 URI。Send a DELETE request to the specified Uri as an asynchronous operation.

DeleteAsync(String, CancellationToken)

以非同步作業的方式,傳送 DELETE 要求和取消權杖至指定的 Uri。Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.

DeleteAsync(Uri)

以非同步作業的方式,將 DELETE 要求傳送至指定的 URI。Send a DELETE request to the specified Uri as an asynchronous operation.

DeleteAsync(Uri, CancellationToken)

以非同步作業的方式,傳送 DELETE 要求和取消權杖至指定的 Uri。Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.

Dispose()

釋放 Unmanaged 資源,並處置 HttpMessageInvoker 所使用的 Managed 資源。Releases the unmanaged resources and disposes of the managed resources used by the HttpMessageInvoker.

(繼承來源 HttpMessageInvoker)
Dispose(Boolean)

釋放 HttpClient 所使用的 Unmanaged 資源,並選擇性處置 Managed 資源。Releases the unmanaged resources used by the HttpClient and optionally disposes of the managed resources.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetAsync(String)

以非同步作業的方式,將 GET 要求傳送至指定的 URI。Send a GET request to the specified Uri as an asynchronous operation.

GetAsync(String, CancellationToken)

以非同步作業的方式,傳送 GET 要求和取消權杖至指定的 Uri。Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.

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)

以非同步作業的方式,傳送 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)

以非同步作業的方式,將 GET 要求傳送至指定的 URI。Send a GET request to the specified Uri as an asynchronous operation.

GetAsync(Uri, CancellationToken)

以非同步作業的方式,傳送 GET 要求和取消權杖至指定的 Uri。Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.

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)

以非同步作業的方式,傳送 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)

將 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)

將 GET 要求傳送至指定的 URI,並透過非同步作業,以位元組陣列形式傳回回應內容。Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
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)

將 GET 要求傳送至指定的 URI,並透過非同步作業,以資料流形式傳回回應內容。Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.

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)

將 GET 要求傳送至指定的 URI,並透過非同步作業,以字串形式傳回回應內容。Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
PatchAsync(String, HttpContent)

以非同步作業的方式,將 PATCH 要求傳送至指定為字串的 URI。Sends a PATCH request to a Uri designated as a string as an asynchronous operation.

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)

以非同步作業的方式傳送 PATCH 要求。Sends a PATCH request as an asynchronous operation.

PatchAsync(Uri, HttpContent, CancellationToken)

以非同步作業的方式,傳送 PATCH 要求和取消語彙基元。Sends a PATCH request with a cancellation token as an asynchronous operation.

PostAsync(String, HttpContent)

以非同步作業的方式,將 POST 要求傳送至指定的 URI。Send a POST request to the specified Uri as an asynchronous operation.

PostAsync(String, HttpContent, CancellationToken)

以非同步作業的方式,傳送 POST 要求和取消語彙基元。Send a POST request with a cancellation token as an asynchronous operation.

PostAsync(Uri, HttpContent)

以非同步作業的方式,將 POST 要求傳送至指定的 URI。Send a POST request to the specified Uri as an asynchronous operation.

PostAsync(Uri, HttpContent, CancellationToken)

以非同步作業的方式,傳送 POST 要求和取消語彙基元。Send a POST request with a cancellation token as an asynchronous operation.

PutAsync(String, HttpContent)

以非同步作業的方式,將 PUT 要求傳送至指定的 URI。Send a PUT request to the specified Uri as an asynchronous operation.

PutAsync(String, HttpContent, CancellationToken)

以非同步作業的方式,傳送 PUT 要求和取消語彙基元。Send a PUT request with a cancellation token as an asynchronous operation.

PutAsync(Uri, HttpContent)

以非同步作業的方式,將 PUT 要求傳送至指定的 URI。Send a PUT request to the specified Uri as an asynchronous operation.

PutAsync(Uri, HttpContent, CancellationToken)

以非同步作業的方式,傳送 PUT 要求和取消語彙基元。Send a PUT request with a cancellation token as an asynchronous operation.

SendAsync(HttpRequestMessage)

以非同步作業的方式,傳送 HTTP 要求。Send an HTTP request as an asynchronous operation.

SendAsync(HttpRequestMessage, CancellationToken)

以非同步作業的方式,傳送 HTTP 要求。Send an HTTP request as an asynchronous operation.

SendAsync(HttpRequestMessage, HttpCompletionOption)

以非同步作業的方式,傳送 HTTP 要求。Send an HTTP request as an asynchronous operation.

SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken)

以非同步作業的方式,傳送 HTTP 要求。Send an HTTP request as an asynchronous operation.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

適用於

另請參閱