WebClient, HttpClient, HttpWebRequest的比較


最近因為要調用webAPI功能,所以開始對目前基於.NET的相關訪問手段進行分析,主要有HttpWebRequest,WebClient和HttpClient三種手段。

HttpWebRequest

這是.NET創建者最初開發用於使用HTTP請求的標准類。使用HttpWebRequest可以讓開發者控制請求/響應流程的各個方面,如 timeouts, cookies, headers, protocols。另一個好處是HttpWebRequest類不會阻塞UI線程。例如,當您從響應很慢的API服務器下載大文件時,您的應用程序的UI不會停止響應。HttpWebRequest通常和WebResponse一起使用,一個發送請求,一個獲取數據。HttpWebRquest更為底層一些,能夠對整個訪問過程有個直觀的認識,但同時也更加復雜一些。以GET請求為例,至少需要五行代碼才能夠實現。

  1. HttpWebRequest http = (HttpWebRequest)WebRequest.Create( "http://example.com");
  2. WebResponse response = http.GetResponse();
  3. Stream stream = response.GetResponseStream();
  4. using (var streamtemn = File.Create("路徑"))
  5. {
  6. stream.CopyTo(streamtemn);
  7. }

這種方法是早期開發者使用的方法,在當前業務中已經很少使用,由於其更加底層,需要處理一些細節,最多可用於框架內部操作。

 WebClient

WebClient是一種更高級別的抽象,是HttpWebRequest為了簡化最常見任務而創建的,使用過程中你會發現他缺少基本的header,timeoust的設置,不過這些可以通過繼承httpwebrequest來實現。相對來說,WebClient比WebRequest更加簡單,它相當於封裝了request和response方法,不過需要說明的是,Webclient和WebRequest繼承的是不同類,兩者在繼承上沒有任何關系。

使用WebClient可能比HttpWebRequest直接使用更慢(大約幾毫秒),但卻更為簡單,減少了很多細節,代碼量也比較少,比如下載文件的代碼,只需要兩行。

  1. using (WebClient webClient = new WebClient())
  2. {
  3. webClient.DownloadFile( "http://example.com", "路徑");
  4. }

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配合 如下 配置代碼,將會提升客戶端的並發能力

            ServicePointManager.DefaultConnectionLimit = 1024;//提升系統外聯的最大並發web訪問數

然后在同樣的程序環境中使用,都使用如下task異步線程池的方式調用
            Task.Run(() =>
                {
//上述代碼段,其中httpclient需要async修飾符
}
實測效果  httpwebrequest  可以達到4000QPS峰值,2000到3000QPS均值(如果服務器有這么快),相同的訪問環境,httpclient只有500平均,800峰值。

結論,httpwebrequest寫web客戶端或者並發度高的搜索爬蟲類軟件,效果遠好於httpclient。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM