C# HttpClient使用 网络(一)
一、异步调用web服务 GetAsync()
1 static void Main(string[] args) 2 { 3 Console.WriteLine("In main before call to GetData!"); 4 GetData(); 5 Console.WriteLine("Back in main after call to GetData!"); 6 Console.ReadKey(); 7 } 8 static async void GetData() 9 { 10 HttpClient httpClient = new HttpClient(); 11 HttpResponseMessage response = null; 12 13 response = await httpClient.GetAsync("http://www.baidu.com"); 14 if(response.IsSuccessStatusCode) 15 { 16 Console.WriteLine("Response status Code :" + response.StatusCode + " " + response.ReasonPhrase); 17 string responseBodyAsText = response.Content.ReadAsStringAsync().Result; 18 Console.WriteLine("Received payload of " + responseBodyAsText.Length + " characters"); 19 Console.WriteLine(responseBodyAsText); 20 } 21 }
二、设置或改变请求标题
1 static void Main(string[] args) 2 { 3 GetData2(); 4 Console.ReadKey(); 5 } 6 7 static void GetData2() 8 { 9 HttpClient httpClient = new HttpClient(); 10 HttpResponseMessage response = null; 11 httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose"); 12 Console.WriteLine("Request Headers:"); 13 EnumerateHeaders(httpClient.DefaultRequestHeaders); 14 Console.WriteLine(); 15 response = httpClient.GetAsync("http://www.baidu.com").Result; 16 if (response.IsSuccessStatusCode) 17 { 18 Console.WriteLine("Response Headers:"); 19 EnumerateHeaders(response.Headers); 20 } 21 } 22 private static void EnumerateHeaders(HttpHeaders headers) 23 { 24 foreach (var header in headers) 25 { 26 var value = ""; 27 foreach (var val in header.Value) 28 { 29 value = val + " "; 30 } 31 Console.WriteLine("Header: " + header.Key + " Value: " + value); 32 } 33 }
三、HttpMessageHandler
1 class Program 2 { 3 4 static void Main(string[] args) 5 { 6 GetData(); 7 Console.ReadKey(); 8 } 9 10 private static void GetData() 11 { 12 HttpClient httpClient = new HttpClient(new MessageHandler("error")); 13 HttpResponseMessage response = null; 14 Console.WriteLine(); 15 response = httpClient.GetAsync("http://services.odata.org/Northwind/Northwind.svc/Regions").Result; 16 Console.WriteLine(response.StatusCode); 17 } 18 } 19 20 public class MessageHandler : HttpClientHandler 21 { 22 string displayMessage = ""; 23 public MessageHandler(string message) 24 { 25 displayMessage = message; 26 } 27 28 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) 29 { 30 Console.WriteLine("In DisplayMessageHandler " + displayMessage); 31 if (displayMessage == "error") 32 { 33 var response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); 34 var tsc = new TaskCompletionSource<HttpResponseMessage>(); 35 tsc.SetResult(response); 36 return tsc.Task; 37 } 38 return base.SendAsync(request, cancellationToken); 39 } 40 41 }
鹰击长空,鱼翔浅底