转载:http://www.diogonunes.com/blog/webclient-vs-httpclient-vs-httpwebrequest/

Just when I was starting to get used to call WebServices through WSDL – like I showed here and here – I had to call a RESTful API. If you don’t know what I’m talking about you’re like me a week ago. Let’s just say that:

  • a WSDL API uses SOAP to exchange XML-encoded data
  • a REST API uses HTTP to exchange JSON-encoded data

That’s a whole new paradigm. Instead of GetObject() and SetObject()methods you have a single url api/object that may receive either an HTTP GETrequest or an HTTP POST request.

The .NET framework offers you three different classes to consume REST APIs: HttpWebRequestWebClientHttpClient. To worsen your analysis paralysisthe open-source community created yet another library called RestSharp. Fear not, I’ll ease your choice.

In the beginning there was… HttpWebRequest

This is the standard class that the .NET creators originally developed to consume HTTP requests. Using HttpWebRequest gives you control over every aspect of the request/response object, like timeouts, cookies, headers, protocols. Another great thing is that HttpWebRequest class does not block the user interface thread. For instance, while you’re downloading a big file from a sluggish API server, your application’s UI will remain responsive.

However, with great power comes great complexity. In order to make a simple GET you need at least five lines of code; we’ll see WebClient does it in two.

HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://example.com");
WebResponse response = http.GetResponse(); MemoryStream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();

The number of ways you can make a mistake with HttpWebRequest is truly astounding. Only use HttpWebRequest if you require the additional low-level control that it offers.

WebClient. Simple.

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. Using WebClient is potentially slower (on the order of a few milliseconds) than using HttpWebRequest directly. But that “inefficiency” comes with huge benefits: it requires less code, is easier to use, and you’re less likely to make a mistake when using it. That same request example is now as simple as:

var client = new WebClient();
var text = client.DownloadString("http://example.com/page.html");

Note: the using statements from both examples were omitted for brevity. You should definitely dispose your web request objects properly.

Don’t worry, you can still specify timeouts, just make sure you follow this workaround.

HttpClient, the best of both worlds

HttpClient provides powerful functionality with better syntax support for newer threading features, e.g. it supports the await keyword. It also enables threaded downloads of files with better compiler checking and code validation. For a complete listing of the advantages and features of this class make sure you read this SO answer.

The only downfall is that it requires .NET Framework 4.5, which many older or legacy machines might not have.

WebClient vs HttpClient vs HttpWebRequest的更多相关文章

  1. 如何选择 WebClient,HttpClient,HttpWebRequest

    当我们在用 .NET 调用 RestAPI 时通常有三种选择,分别为:WebClient, HttpWebRequest,HttpClient,这篇文章我们将会讨论如何使用这三种方式去调用 RestA ...

  2. HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之间的区别

    HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 今天我们来聊一下他们之间的关系与区别. HttpRequest 类 .NET Fr ...

  3. webrequest、httpwebrequest、webclient、HttpClient 四个类的区别

    一.在 framework 开发环境下: webrequest.httpwebreques  都是基于Windows Api 进行包装, webclient 是基于webrequest 进行包装:(经 ...

  4. .Net5下WebRequest、WebClient、HttpClient是否还存在使用争议?

    WebRequest.WebClient.HttpClient 是C#中常用的三个Http请求的类,时不时也会有人发表对这三个类使用场景的总结,本人是HttpClient 一把梭,也没太关注它们的内部 ...

  5. C#获取网页内容 (WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)

    获取网页数据有很多种方式.在这里主要讲述通过WebClient.WebBrowser和HttpWebRequest/HttpWebResponse三种方式获取网页内容. 这里获取的是包括网页的所有信息 ...

  6. C#中HttpWebRequest、WebClient、HttpClient的使用

    HttpWebRequest: 命名空间: System.Net,这是.NET创建者最初开发用于使用HTTP请求的标准类.使用HttpWebRequest可以让开发者控制请求/响应流程的各个方面,如  ...

  7. webclient 和httpclient 应用

    //webclient应用 MyImageServerEntities db = new MyImageServerEntities(); public ActionResult Index() { ...

  8. WebClient和HttpClient, 以及webapi上传图片

    httppost请求. applicationkey/x-www-form-urlencoded请求: Email=321a&Name=kkfewwebapi里面, 如果用实体, 能接受到. ...

  9. C#网页采集数据的几种方式(WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)

    一.通过WebClient获取网页内容 这是一种很简单的获取方式,当然,其它的获取方法也很简单.在这里首先要说明的是,如果为了实际项目的效率考虑,需要考虑在函数中分配一个内存区域.大概写法如下 //M ...

随机推荐

  1. bzoj4639 博士的选取器

    题意 给出一个长度为n的正整数序列,要求把它划分成若干个连续的区间,使得每个区间的数字之和都不超过给定的lim.最后的代价等于每个区间的最大值之和.求最小代价.n<=300000 分析 定义f[ ...

  2. 【bzoj3774】最优选择 网络流最小割

    题目描述 小N手上有一个N*M的方格图,控制某一个点要付出Aij的代价,然后某个点如果被控制了,或者他周围的所有点(上下左右)都被控制了,那么他就算是被选择了的.一个点如果被选择了,那么可以得到Bij ...

  3. DataTable 转换 DataSet

    DataTable dt = resuylt.Copy(); var dsR = new DataSet(); ds.Tables.Add(dt);

  4. python基础----__slots__方法、__call__方法

    ''' 1.__slots__是什么:是一个类变量,变量值可以是列表,元祖,或者可迭代对象,也可以是一个字符串(意味着所有实例只有一个数据属性) 2.引子:使用点来访问属性本质就是在访问类或者对象的_ ...

  5. mysql三-6:完整性约束

    一 介绍 约束条件与数据类型的宽度一样,都是可选参数 作用:用于保证数据的完整性和一致性 主要分为: PRIMARY KEY (PK) 标识该字段为该表的主键,可以唯一的标识记录 FOREIGN KE ...

  6. git使用笔记(十四)cat-file

    By francis_hao    Mar 18,2018   git cat-file :提供仓库中对象实体的类型.大小和内容的信息 概要 git cat-file (-t | -s | -e | ...

  7. 通过ida dump Uinity3D的加密dll

    声明: 1.本文转载自:http://www.52pojie.cn/thread-398266-1-1.html,仅供自己保存使用,高手勿喷 2.欢迎学习交流 通过ida dump Uinity3D的 ...

  8. Tensorboard教程:Tensorflow命名空间与计算图可视化

    Tensorflow命名空间与计算图可视化 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 强烈推荐Tensorflow实战Google深度学习框架 实验平台: Tensorflow ...

  9. JS笔记-强化版1

    1.函数:可以理解为-命令,做一些事~~       function abc(){ // 肯定不会主动执行的!       ……       }       直接调用:abc();       事件 ...

  10. spring boot 2.0.3+spring cloud (Finchley)8、微服务监控Spring Boot Admin

    参考:Spring Boot Admin 2.0 上手 Spring Boot Admin 用于管理和监控一个或多个Spring Boot程序,在 Spring Boot Actuator 的基础上提 ...