HttpClient實現請求

來源:互聯網
上載者:User

標籤:get   .com   code   and   sync   ip)   orm   com   handle   

 1  /// <summary> 2         ///     HttpClient實現Get請求(非同步) 3         /// </summary> 4         private static async void DoGet() 5         { 6             var url = "http://localhost:5555/api/Test/Get?id=1"; 7             //建立HttpClient(注意傳入HttpClientHandler)   8             var handler = new HttpClientHandler {AutomaticDecompression = DecompressionMethods.GZip}; 9 10             using (var http = new HttpClient(handler))11             {12                 //await非同步等待回應  13                 var response = await http.GetAsync(url);14                 //確保HTTP成功狀態值  15                 response.EnsureSuccessStatusCode();16 17                 //await非同步讀取最後的JSON(注意此時gzip已經被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)  18                 Console.WriteLine(await response.Content.ReadAsStringAsync());19             }20         }21 22         /// <summary>23         ///     HttpClient實現Put請求(非同步)24         /// </summary>25         private static async void DoPut()26         {27             var userId = 6;28             var url = "http://localhost:5555/api/put/register?userid=" + userId;29 30             //設定HttpClientHandler的AutomaticDecompression  31             var handler = new HttpClientHandler {AutomaticDecompression = DecompressionMethods.GZip};32             //建立HttpClient(注意傳入HttpClientHandler)  33             using (var http = new HttpClient(handler))34             {35                 //使用FormUrlEncodedContent做HttpContent  36                 var content = new FormUrlEncodedContent(new Dictionary<string, string>37                 {38                     {"UserName", "修改胡景寶"},39                     {"UserEmail", "[email protected]"} 40                 });41 42                 //await非同步等待回應  43 44                 var response = await http.PutAsync(url, content);45                 //確保HTTP成功狀態值  46                 response.EnsureSuccessStatusCode();47                 //await非同步讀取最後的JSON(注意此時gzip已經被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip)  48                 Console.WriteLine(await response.Content.ReadAsStringAsync());49             }50         }

 

HttpClient實現請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.