System.Net.Http 是微軟推出的最新的 HTTP 應用程序的編程接口, 微軟稱之爲「現代化的 HTTP 編程接口」, 主要提供以下內容:web
1. 用戶經過 HTTP 使用現代化的 Web Service 的客戶端組件;編程
2. 可以同時在客戶端與服務端同時使用的 HTTP 組件(好比處理 HTTP 標頭和消息), 爲客戶端和服務端提供一致的編程模型。api
命名空間 System.Net.Http 以及 System.Net.Http.Headers 提供了以下內容:緩存
1. HttpClient 發送和接收 HTTP 請求與響應;服務器
2. HttpRequestMessage and HttpResponseMessage 封裝了 RFC 2616 定義的 HTTP 消息;多線程
3. HttpHeaders 封裝了 RFC 2616 定義的 HTTP 標頭;app
4. HttpClientHandler 負責生成HTTP響應消息的HTTP處理程序。asp.net
System.Net.Http 可以處理多種類型的 RFC 2616 定義的 HTTP 實體正文, 以下圖所示:ide
此外, System.Net.Http 對 HTTP 消息的處理採用了職責鏈模式, 這裏有一遍不錯的介紹, 這裏就再也不多說了。函數
HttpClient 組件類實例爲一個會話發送 HTTP 請求。 HttpClient 實例設置爲集合會應用於該實例執行的全部請求。 此外,每 HttpClient 實例使用本身的鏈接池,隔離其餘 HttpClient實例的執行請求。 HttpClient 也是更具體的 HTTP 客戶端的基類。
默認狀況下,使用 HttpWebRequest 向服務器發送請求。 這一行爲可經過在接受一個HttpMessageHandler實例做爲參數的構造函數重載中指定不一樣的通道來更改。
若是須要身份驗證或緩存的功能,WebRequestHandler 可以使用配置項和實例傳遞給構造函數。 返回的處理程序傳遞到採用 HttpMessageHandler 參數的某構造進行返回參數傳遞。
若是使用 HttpClient 和相關組件類的 app 在 System.Net.Http 命名空間用於下載大量數據 (可達 50 MB 或更多),則應用程序應這些下載的流和不使用默認值緩衝區。 若是使用默認值緩衝區客戶端內存使用量會很是大,可能會致使顯着下降的性能。
對於 HttpClient的基本使用方法,示例代碼以下:
//聲明HttpClient HttpClient client = new HttpClient { BaseAddress = new Uri("http://www.163.com") }; //多線程中跨線程進行信息顯示委託 public delegate void ShowMsgDelegate(string text); public void ShowMsgText(string text) { txtMsg.Text=text; } //信息顯示 private void ShowMessage(string msg) { if (this.InvokeRequired) { this.Invoke(new ShowMsgDelegate(ShowMsgText), msg); } else { ShowMsgText(msg); } } // Get form data to server private void btnGet_Click(object sender, EventArgs e) { // Get string from server client.GetStringAsync("browserhttp/").ContinueWith(t => { if (t.IsFaulted) { ShowMessage("返回信息錯誤:" + t.Result); } else { ShowMessage("成功:" + t.Result); } }); } // Post form data to server private void btnPost_Click(object sender, EventArgs e) { var param = new Dictionary<string, string> { {"Name", "TOM Post"}, {"Age", "11"}, {"Birthday", DateTime.Now.ToString("yyyyMMdd")} }; client.PostAsync("browserhttp/", new FormUrlEncodedContent(param)).ContinueWith(t => { ShowMsgDelegate showmsg = new ShowMsgDelegate(ShowMsgText); if (t.IsFaulted) { ShowMessage("返回信息錯誤:" + t.Result); } else { HttpResponseMessage response = t.Result; ShowMessage(response.StatusCode.ToString()); } }); } // PUT to update private void btnPut_Click(object sender, EventArgs e) { var param = new Dictionary<string, string> { {"Id", "10" }, {"Name", "Tom Post"}, {"Age", "10"}, {"Birthday", DateTime.Now.ToString("yyyyMMdd")} }; client.PutAsync("clienthttp/1", new FormUrlEncodedContent(param)).ContinueWith(t => { if (t.IsFaulted) { ShowMessage("返回信息錯誤:" + t.Result); } else { HttpResponseMessage response = t.Result; ShowMessage(response.StatusCode.ToString()); } }); } // DELETE private void btnDel_Click(object sender, EventArgs e) { client.DeleteAsync("clienthttp/1").ContinueWith(t => { if (t.IsFaulted) { ShowMessage("返回信息錯誤:" + t.Result); } else { HttpResponseMessage response = t.Result; ShowMessage(response.StatusCode.ToString()); } }); }
支持職責鏈模式的 MessageProcessingHandler ,MessageProcessingHandler - 一種基本的 HTTP 消息處理程序。這是最容易進行派生的處理程序,應該做爲大多數自定義處理程序的起點。 自已定義了一個新的MessageProcessingHandler處理程序,以下面的示例代碼所示:
public class CustomProcessingHandler : MessageProcessingHandler { protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken) { if (request.Method != HttpMethod.Get && request.Method != HttpMethod.Post) { request.Headers.TryAddWithoutValidation("RequestMethod", request.Method.Method); request.Method = HttpMethod.Post; } return request; } protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) { var request = response.RequestMessage; if (request.Headers.Contains("RequestMethod")) { IEnumerable<string> values; if (request.Headers.TryGetValues("RequestMethod", out values)) { request.Method = new HttpMethod(values.First()); } } return response; } } 使用起來也是很是簡單的: private void btnCustom_Click(object sender, EventArgs e) { var customHandler = new CustomProcessingHandler { InnerHandler = new HttpClientHandler() }; var client = new HttpClient(customHandler, true) { BaseAddress = new Uri("http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl") }; var task = client.GetAsync(client.BaseAddress); task.Result.EnsureSuccessStatusCode(); HttpResponseMessage response = task.Result; txtStatusCode.Text = response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine; txtStatusText.Text = "請求返回結果以下 ..."; var result = response.Content.ReadAsStringAsync(); txtMsg.Text = result.Result; ; }