HttpClient實現請求
阿新 • • 發佈:2017-07-04
oge ces 自動 sco dict automatic gas sin 使用
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; 28var 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實現請求