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。
原文地址:https://www.cnblogs.com/cuihongyu3503319/p/13993693.html