###### tags: `學習記錄` `C#` # HttpClient [官方文件](https://docs.microsoft.com/zh-tw/dotnet/api/system.net.http.httpclient?view=net-6.0) 提供類別,用來傳送 HTTP 要求,以及從 URI 所識別的資源接收 HTTP 回應。 ```csharp= // 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); } } ``` ## 線程安全 下列方法為安全線程: 1. CancelPendingRequests 1. DeleteAsync 1. GetAsync 1. GetByteArrayAsync 1. GetStreamAsync 1. GetStringAsync 1. PostAsync 1. PutAsync 1. SendAsync 1. PatchAsync ## 使用方式 HttpClient 的目的是要具現化一次,並在應用程式的整個生命週期中重複使用。 具現化每個要求的 HttpClient 類別,將會耗盡繁重負載下可用的通訊端數目。 這會導致 >socketexception 錯誤。 以下是正確使用 HttpClient 的範例。 ```csharp= public class GoodController : ApiController { private static readonly HttpClient HttpClient; static GoodController() { HttpClient = new HttpClient(); } } ``` ## 有趣的屬性 ### Timeout 取得或設定要求逾時前等候的時間長度。 ## 有趣的方法 ### GetStringAsync(String) 將 GET 要求傳送至指定的 URI,並透過非同步作業,以字串形式傳回回應內容。