最近因為要調用webAPI功能,所以開始對目前基於.NET的相關訪問手段進行分析,主要有HttpWebRequest,WebClient和HttpClient三種手段。
HttpWebRequest
這是.NET創建者最初開發用於使用HTTP請求的標准類。使用HttpWebRequest可以讓開發者控制
請求/響應流程的各個方面,如 timeouts, cookies, headers, protocols。另一個好處是HttpWebRequest類不會阻塞UI線程。例如,當您從響應很慢的API服務器下載大文件時,您的應用程序的UI不會停止響應。HttpWebRequest通常和WebResponse一起使用,一個發送請求,一個獲取數據。HttpWebRquest更為底層一些,能夠對整個訪問過程有個直觀的認識,但同時也更加復雜一些。以GET請求為例,至少需要五行代碼才能夠實現。
-
HttpWebRequest http = (HttpWebRequest)WebRequest.Create( "http://example.com");
-
WebResponse response = http.GetResponse();
-
Stream stream = response.GetResponseStream();
-
using (var streamtemn = File.Create("路徑"))
-
{
-
stream.CopyTo(streamtemn);
-
}
這種方法是早期開發者使用的方法,在當前業務中已經很少使用,由於其更加底層,需要處理一些細節,最多可用於框架內部操作。
WebClient
WebClient
是一種更高級別的抽象,是HttpWebRequest
為了簡化最常見任務而創建的,使用過程中你會發現他缺少基本的header,timeoust的設置,不過這些可以通過繼承httpwebrequest來實現。相對來說,WebClient比WebRequest更加簡單,它相當於封裝了request和response方法,不過需要說明的是,Webclient和WebRequest繼承的是不同類,兩者在繼承上沒有任何關系。
使用WebClient
可能比HttpWebRequest
直接使用更慢(大約幾毫秒),但卻更為簡單,減少了很多細節,代碼量也比較少,比如下載文件的代碼,只需要兩行。
-
using (WebClient webClient = new WebClient())
-
{
-
webClient.DownloadFile( "http://example.com", "路徑");
-
}
WebClient主要面向了WEB網頁場景,在模擬Web操作時使用較為方便,但用在RestFul場景下卻比較麻煩,這時候就需要HttpClient出馬了。
HttpClient
目前業務上使用的比較多的是HttpClient,它適合用於多次請求操作,一般設置好默認頭部后,可以進行重復多次的請求,基本上用一個實例可以提交任何的HTTP請求。此外,HttpClient提供了異步支持,可以輕松配合async await 實現異步請求。
下表是三者一些區別
HttpWebRequset | WebClient | HttpClient | |
命名空間 | System.Net | System.Net | System.Net.Http |
繼承類 | WebRequest | Component | HttpMessageInvoker |
支持url轉向 | 是 | 否 | 是 |
支持cookie和session | 是 | 否 | 否 |
支持用戶代理服務器 | 是 | 否 | 是 |
使用復雜度 | 高 | 低 | 低 |
實測 c# .net 中 httpwebrequest 和 httpclient 性能 區別 對比
以下是httpclient的代碼
using (var http = new HttpClient())
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"token", steptoken},
{"id", steporderid},
{"driverId", stepdriverid}
});
s_totalwebrequest0++;
var response = await http.PostAsync("http://" + s_webapipro + "/denyOrder", content);
string res = await response.Content.ReadAsStringAsync();
s_totalwebrequest1++;
JObject obj = JObject.Parse(res);
}
以下是httpwebrequest的代碼
string url = "http://" + GetWebApiPro() + "/denyOrder";
string postData = "token=" + steptoken + "&id=" + steporderid + "&driverId=" + stepdriverid;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = "post";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
System.IO.Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string res = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
JObject obj = JObject.Parse(res);
httpwebrequest配合 如下 配置代碼,將會提升客戶端的並發能力
{