zoukankan      html  css  js  c++  java
  • HttpWebRequest和WebClient的区别

     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()跟界面进行通讯。

      1 //body是要传递的参数,格式"roleId=1&uid=2"
      2 //post的cotentType填写:
      3 //"application/x-www-form-urlencoded"
      4 //soap填写:"text/xml; charset=utf-8"
      5 public static string PostHttp(string url, string body, string contentType)
      6 {
      7 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
      8 
      9 httpWebRequest.ContentType = contentType;
     10 httpWebRequest.Method = "POST";
     11 httpWebRequest.Timeout = 20000;
     12 
     13 byte[] btBodys = Encoding.UTF8.GetBytes(body);
     14 httpWebRequest.ContentLength = btBodys.Length;
     15 httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
     16 
     17 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
     18 StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
     19 string responseContent = streamReader.ReadToEnd();
     20 
     21 httpWebResponse.Close();
     22 streamReader.Close();
     23 httpWebRequest.Abort();
     24 httpWebResponse.Close();
     25 
     26 return responseContent;
     27 }
     28 
     29 POST方法(httpWebRequest)
     30 
     31  
     32 
     33  
     34 
     35 /// <summary>
     36 /// 通过WebClient类Post数据到远程地址,需要Basic认证;
     37 /// 调用端自己处理异常
     38 /// </summary>
     39 /// <param name="uri"></param>
     40 /// <param name="paramStr">name=张三&age=20</param>
     41 /// <param name="encoding">请先确认目标网页的编码方式</param>
     42 /// <param name="username"></param>
     43 /// <param name="password"></param>
     44 /// <returns></returns>
     45 public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)
     46 {
     47 if (encoding == null)
     48 encoding = Encoding.UTF8;
     49 
     50 string result = string.Empty;
     51 
     52 WebClient wc = new WebClient();
     53 
     54 // 采取POST方式必须加的Header
     55 wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
     56 
     57 byte[] postData = encoding.GetBytes(paramStr);
     58 
     59 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
     60 {
     61 wc.Credentials = GetCredentialCache(uri, username, password);
     62 wc.Headers.Add("Authorization", GetAuthorization(username, password));
     63 }
     64 
     65 byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流
     66 return encoding.GetString(responseData);// 解码 
     67 }
     68 
     69 POST方法(WebClient)
     70 
     71  
     72 
     73 public static string GetHttp(string url, HttpContext httpContext)
     74 {
     75 string queryString = "?";
     76 
     77 foreach (string key in httpContext.Request.QueryString.AllKeys)
     78 {
     79 queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
     80 }
     81 
     82 queryString = queryString.Substring(0, queryString.Length - 1);
     83 
     84 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);
     85 
     86 httpWebRequest.ContentType = "application/json";
     87 httpWebRequest.Method = "GET";
     88 httpWebRequest.Timeout = 20000;
     89 
     90 //byte[] btBodys = Encoding.UTF8.GetBytes(body);
     91 //httpWebRequest.ContentLength = btBodys.Length;
     92 //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
     93 
     94 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
     95 StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
     96 string responseContent = streamReader.ReadToEnd();
     97 
     98 httpWebResponse.Close();
     99 streamReader.Close();
    100 
    101 return responseContent;
    102 }
    103 
    104 Get方法(HttpWebRequest)
    105 
    106  
    107 
    108  
    109 
    110  
    111 
    112 /// <summary>
    113 /// 通过 WebRequest/WebResponse 类访问远程地址并返回结果,需要Basic认证;
    114 /// 调用端自己处理异常
    115 /// </summary>
    116 /// <param name="uri"></param>
    117 /// <param name="timeout">访问超时时间,单位毫秒;如果不设置超时时间,传入0</param>
    118 /// <param name="encoding">如果不知道具体的编码,传入null</param>
    119 /// <param name="username"></param>
    120 /// <param name="password"></param>
    121 /// <returns></returns>
    122 public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
    123 {
    124 string result = string.Empty;
    125 
    126 WebRequest request = WebRequest.Create(new Uri(uri));
    127 
    128 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
    129 {
    130 request.Credentials = GetCredentialCache(uri, username, password);
    131 request.Headers.Add("Authorization", GetAuthorization(username, password));
    132 }
    133 
    134 if (timeout > 0)
    135 request.Timeout = timeout;
    136 
    137 WebResponse response = request.GetResponse();
    138 Stream stream = response.GetResponseStream();
    139 StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding);
    140 
    141 result = sr.ReadToEnd();
    142 
    143 sr.Close();
    144 stream.Close();
    145 
    146 return result;
    147 }
    148 
    149 #region # 生成 Http Basic 访问凭证 #
    150 
    151 private static CredentialCache GetCredentialCache(string uri, string username, string password)
    152 {
    153 string authorization = string.Format("{0}:{1}", username, password);
    154 
    155 CredentialCache credCache = new CredentialCache();
    156 credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));
    157 
    158 return credCache;
    159 }
    160 
    161 private static string GetAuthorization(string username, string password)
    162 {
    163 string authorization = string.Format("{0}:{1}", username, password);
    164 
    165 return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
    166 }
    167 
    168 #endregion
    169 
    170 basic验证的WebRequest/WebResponse
     

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

  • 相关阅读:
    webstrom破解的问题
    redis高级应用(1)
    linux之软链接、硬链接
    爬虫之scrapy、scrapy-redis
    爬虫之xpath、selenuim
    爬虫之Beautifulsoup模块
    爬虫之Reuqests模块使用
    测试项目配置
    Cleary基础
    Redis基础
  • 原文地址:https://www.cnblogs.com/lijIT/p/4353868.html
Copyright © 2011-2022 走看看