[C#]使用 HttpClient 的正確姿勢

JoJo
4 min readNov 19, 2023

--

在C#中,HttpClient是一個用於發送HTTP請求的類別,它提供了一個簡潔而強大的介面,用於與Web服務進行通信。以下是HttpClient的基本用法以及一些使用上的注意事項:

基本用法:

  1. 建立 HttpClient 實例:
using System.Net.Http;

HttpClient httpClient = new HttpClient();

2. 發送 GET 請求:

string apiUrl = "https://api.example.com/data";
HttpResponseMessage response = await httpClient.GetAsync(apiUrl);

if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
// 處理回應內容
}

3. 發送 POST 請求:

string apiUrl = "https://api.example.com/create";
string jsonContent = "{\"key\":\"value\"}";
HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");

HttpResponseMessage response = await httpClient.PostAsync(apiUrl, httpContent);

if (response.IsSuccessStatusCode)
{
// 處理回應內容
}

注意事項:

  1. 管理 HttpClient 的生命週期: 不應該在每次發送請求時都創建新的 HttpClient 實例,因為這樣會導致資源浪費。應該重複使用同一個實例,或者使用 HttpClientFactory 進行管理。
// 錯誤的做法
// using (HttpClient httpClient = new HttpClient())
// {
// // 發送請求
// }

// 正確的做法
private static readonly HttpClient _httpClient = new HttpClient();

// 使用 _httpClient 進行請求

2. 非同步操作: HttpClient 提供非同步方法,應優先使用異步操作以充分發揮性能。例如,使用 GetAsync 而不是 Get

// 非異步操作(不推薦)
// HttpResponseMessage response = httpClient.GetAsync(apiUrl).Result;

// 異步操作
HttpResponseMessage response = await httpClient.GetAsync(apiUrl);

3. 釋放資源: 當不再需要 HttpClient 實例時,應該調用 Dispose 方法釋放資源。或者,使用 HttpClientFactory 管理生命週期,以確保在需要時適當地釋放資源。

_httpClient.Dispose();

4. 處理例外狀況: 考慮處理可能發生的例外狀況,如網路連線問題、伺服器錯誤等。使用 try-catch 塊捕獲 HttpRequestException 或其他可能的異常。

try
{
HttpResponseMessage response = await httpClient.GetAsync(apiUrl);
// 處理回應內容
}
catch (HttpRequestException ex)
{
// 處理例外狀況
}

--

--