基于HttpClient 类常见的API代码示例
关于HttpClient类
-
命名空间:System.Net.Http
-
程序集:System.Net.Http.dll
-
介绍:提供基本类,用于发送 HTTP 请求和接收来自通过 URI 确认的资源的 HTTP 响应。
-
继承关系:Object --> HttpMessageInvoker --> HttpClient
-
示例 使用
async Task Main()
入口点。 该功能需要 c # 7.1 或更高版本。// 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); } }
HttpClient实例构造函数参数设置
static WebAPI(){ httpClient = SetHttpClient(); httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0"); httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0"); httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");//,return=representation httpClient.DefaultRequestHeaders.Connection.Add("keep-alive"); //http预热 httpClient.SendAsync(new HttpRequestMessage { Method = new HttpMethod("HEAD"), RequestUri &