HttpWebRequest和WebClient的区别(From Linzheng):

1,HttpWebRequest是个抽象类,所以无法new的,需要调用HttpWebRequest.Create();
2,其Method指定了请求类型,这里用的GET,还有POST;也可以指定ConentType;
3,其请求的Uri必须是绝对地址;
4,其请求是异步回调方式的,从BeginGetResponse开始,并通过AsyncCallback指定回调方法;
5,WebClient 方式使用基于事件的异步编程模型,在HTTP响应返回时引发的WebClient回调是在UI线程中调用的,因此可用于更新UI元素的属性,例如把 HTTP响应中的数据绑定到UI的指定控件上进行显示。HttpWebRequest是基于后台进程运行的,回调不是UI线程,所以不能直接对UI进行操作,通常使用Dispatcher.BeginInvoke()跟界面进行通讯。

 //body是要传递的参数,格式"roleId=1&uid=2"
//post的cotentType填写:
//"application/x-www-form-urlencoded"
//soap填写:"text/xml; charset=utf-8"
public static string PostHttp(string url, string body, string contentType)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = contentType;
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = ; byte[] btBodys = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, , btBodys.Length); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd(); httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close(); return responseContent;
} POST方法(httpWebRequest) /// <summary>
/// 通过WebClient类Post数据到远程地址,需要Basic认证;
/// 调用端自己处理异常
/// </summary>
/// <param name="uri"></param>
/// <param name="paramStr">name=张三&age=20</param>
/// <param name="encoding">请先确认目标网页的编码方式</param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)
{
if (encoding == null)
encoding = Encoding.UTF8; string result = string.Empty; WebClient wc = new WebClient(); // 采取POST方式必须加的Header
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); byte[] postData = encoding.GetBytes(paramStr); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
wc.Credentials = GetCredentialCache(uri, username, password);
wc.Headers.Add("Authorization", GetAuthorization(username, password));
} byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流
return encoding.GetString(responseData);// 解码
} POST方法(WebClient) public static string GetHttp(string url, HttpContext httpContext)
{
string queryString = "?"; foreach (string key in httpContext.Request.QueryString.AllKeys)
{
queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
} queryString = queryString.Substring(, queryString.Length - ); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString); httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = ; //byte[] btBodys = Encoding.UTF8.GetBytes(body);
//httpWebRequest.ContentLength = btBodys.Length;
//httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd(); httpWebResponse.Close();
streamReader.Close(); return responseContent;
} Get方法(HttpWebRequest) /// <summary>
/// 通过 WebRequest/WebResponse 类访问远程地址并返回结果,需要Basic认证;
/// 调用端自己处理异常
/// </summary>
/// <param name="uri"></param>
/// <param name="timeout">访问超时时间,单位毫秒;如果不设置超时时间,传入0</param>
/// <param name="encoding">如果不知道具体的编码,传入null</param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
{
string result = string.Empty; WebRequest request = WebRequest.Create(new Uri(uri)); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
request.Credentials = GetCredentialCache(uri, username, password);
request.Headers.Add("Authorization", GetAuthorization(username, password));
} if (timeout > )
request.Timeout = timeout; WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding); result = sr.ReadToEnd(); sr.Close();
stream.Close(); return result;
} #region # 生成 Http Basic 访问凭证 # private static CredentialCache GetCredentialCache(string uri, string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password); CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password)); return credCache;
} private static string GetAuthorization(string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password); return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
} #endregion basic验证的WebRequest/WebResponse
 

备注:引自  http://www.cnblogs.com/shadowtale/p/3372735.html

HttpWebRequest和WebClient的区别的更多相关文章

  1. C# HttpWebRequest和WebClient的区别 通过WebClient/HttpWebRequest实现http的post/get方法

    一 HttpWebReques1,HttpWebRequest是个抽象类,所以无法new的,需要调用HttpWebRequest.Create();2,其Method指定了请求类型,这里用的GET,还 ...

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

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

  3. Linux中用HttpWebRequest或WebClient访问远程https路径

    要想在Linux中用HttpWebRequest或WebClient访问远程https路径,需要作如下处理: 1,更新linux根证书(只需一次,在安装mono或安装jexus独立版后执行) sudo ...

  4. WebClient, HttpClient, HttpWebRequest ,RestSharp之间的区别与抉择

    NETCore提供了三种不同类型用于生产的REST API: HttpWebRequest;WebClient;HttpClient,开源社区创建了另一个名为RestSharp的库.如此多的http库 ...

  5. WebRequest/HttpWebRequest/HttpRequest/WebClient/HttpClient的区别

    1.WebRequest和HttpWebRequest WebRequest 的命名空间是: System.Net ,它是HttpWebRequest的抽象父类(还有其他子类如FileWebReque ...

  6. HttpWebRequest、WebClient、RestSharp、HttpClient区别和用途

    HttpWebRequest 已经不推荐直接使用了,这已经作为底层机制,不适合业务代码使用,比如写爬虫的时候WebClient 不想为http细节处理而头疼的coder而生,由于内部已经处理了通用设置 ...

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

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

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

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

  9. HttpWebRequest和WebClient的用法

    //通过web方式,从远程服务器端下载文件: public static void DownLoad(string Url, string FileName, string machinetype) ...

随机推荐

  1. hdu 1524 A Chess Game 博弈

    题目链接 给出一个有向无环图, 上面放有一些棋子, 两个人轮流移动棋子, 当一个人无法移动时, 算输. 求出每一个点的sg值, 异或就可以.出度为0的点sg值为0. #include<bits/ ...

  2. 【原创】JPEG图像密写研究(三) 数据流译码

    [原创]这次更新比较慢,译码过程比想象中复杂一些,更主要是译出来的DCT系数无法确定是否正确,要想验证就需要再进行正向压缩编码,再次形成jpeg图像验证正确,后续工作正在开展,这里就说一说译码的主要思 ...

  3. issues about Facebook Login

    在学习The complete iOS 9 Developer Course - Build 18 Apps 中的Letture134-Facebook Login,需要整合(integrate)Pa ...

  4. 成为 Linux 内核高手的四个方法

    (之前我在 CUSEC 网站发表了关于内核并不可怕的一篇文章,本文是后续.) 我曾经问别人如何开始内核编程的学习,他们基本上都说:1. 如果你不需要了解内核是如何为你工作的,你为何要尝试呢?2. 你应 ...

  5. java的控制流程

    1.顺序结构顺序结构就是指按语句执行的先后顺序,或者说语句出现的先后顺序逐条执行程序语句.语句块,完全是按照程序平台的执行约定进行的,比如第一个 HelloWorld程序:public class H ...

  6. [C/C++标准库]_[0基础]_[优先队列priority_queue的使用]

    std::priority_queue 场景: 1. 对于一个任务队列,任务的优先级由任务的priority属性指明,这时候就须要优先级越高的先运行.而queue并没有排序功能,这时priority_ ...

  7. c++程序内存泄露检測工具

    功能: 用于检測c++程序的内存泄露. 原理: 事实上非常easy,就是通过函数的重载机制,捕获应用程序的new, new[] , delete , delete[], malloc,calloc,f ...

  8. word排版论文小结

    毕业论文如何用WORD排版 本人折腾了一晚上看别人的百度经验,做个总结,方便后人看懂,其实特别简单 用WORD自动生成页码 第一种情况:从第一页或者从第二页开始设置页码 这种情况只要“插入-> ...

  9. Asp.Net MVC4.0 官方教程 入门指南之五--控制器访问模型数据

    Asp.Net MVC4.0 官方教程 入门指南之五--控制器访问模型数据 在这一节中,你将新创建一个新的 MoviesController类,并编写代码,实现获取影片数据和使用视图模板在浏览器中展现 ...

  10. POJ2823 Sliding Window(单调队列)

    单调队列,我用deque维护.这道题不难写,我第二次写单调队列,1次AC. -------------------------------------------------------------- ...