HttpRequestHelp

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using System.Net;
   5:  using System.IO;
   6:  using System.Web;
   7:  using System.Text.RegularExpressions;
   8:   
   9:  public class HttpRequestHelp
  10:  {
  11:   
  12:   
  13:      #region  获取登陆的Cookies信息
  14:   
  15:      /// <summary>登录,获取Cookice信息
  16:      /// </summary>
  17:      /// <param name="url">网址</param>
  18:      /// <param name="paramList">参数</param>
  19:      /// <param name="cookieCon">Cookice信息</param>
  20:      /// <returns>返回登陆的页面</returns>
  21:      public static string Login(string url, string paramList, ref CookieContainer cookieCon)
  22:      {
  23:          HttpWebResponse res = null;
  24:          string strResult = "";
  25:          try
  26:          {
  27:              HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  28:              req.Method = "POST";
  29:              req.ContentType = "application/x-www-form-urlencoded";
  30:              req.AllowAutoRedirect = false;
  31:              cookieCon = new CookieContainer();
  32:              req.CookieContainer = cookieCon;
  33:              StringBuilder UrlEncoded = new StringBuilder();
  34:              Char[] reserved = { '?', '=', '&' };
  35:              byte[] SomeBytes = null;
  36:              if (paramList != null)
  37:              {
  38:                  int i = 0, j;
  39:                  while (i < paramList.Length)
  40:                  {
  41:                      j = paramList.IndexOfAny(reserved, i);
  42:                      if (j == -1)
  43:                      {
  44:                          UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length - i)));
  45:                          break;
  46:                      }
  47:                      UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j - i)));
  48:                      UrlEncoded.Append(paramList.Substring(j, 1));
  49:                      i = j + 1;
  50:                  }
  51:                  SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
  52:                  req.ContentLength = SomeBytes.Length;
  53:                  Stream newStream = req.GetRequestStream();
  54:                  newStream.Write(SomeBytes, 0, SomeBytes.Length);
  55:                  newStream.Close();
  56:              }
  57:              else
  58:              {
  59:                  req.ContentLength = 0;
  60:              }
  61:   
  62:              res = (HttpWebResponse)req.GetResponse();
  63:              string cookieheader = req.CookieContainer.GetCookieHeader(new Uri(url));//cookies头
  64:              Stream ReceiveStream = res.GetResponseStream();
  65:              Encoding encode = System.Text.Encoding.GetEncoding("GBK");
  66:              StreamReader sr = new StreamReader(ReceiveStream, encode);
  67:              Char[] read = new Char[256];
  68:              int count = sr.Read(read, 0, 256);
  69:              while (count > 0)
  70:              {
  71:                  String str = new String(read, 0, count);
  72:                  strResult += str;
  73:                  count = sr.Read(read, 0, 256);
  74:              }
  75:          }
  76:          catch (Exception e)
  77:          {
  78:              strResult = e.ToString();
  79:          }
  80:          finally
  81:          {
  82:              if (res != null)
  83:              {
  84:                  res.Close();
  85:              }
  86:          }
  87:          return strResult;
  88:      }
  89:      /// <summary>
  90:      /// 获取页面HTML
  91:      /// </summary>
  92:      /// <param name="url">网址</param>
  93:      /// <param name="paramList">参数</param>
  94:      /// <param name="cookieCon">Cookice信息</param>
  95:      /// <returns>返回要处理的页面</returns>
  96:      public static string getPage(string url, string paramList, ref CookieContainer cookieCon)
  97:      {
  98:          HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  99:          //req.Headers["If-None-Match"] = "36d0ed736e88c71:d9f";
 100:          //req.Referer = "http://bbs.dospy.com";
 101:          //  CookieContainer cookieCon =cookieCon;
 102:          req.CookieContainer = cookieCon;
 103:          //req.CookieContainer.SetCookies(new Uri(url), cookieheader);
 104:          HttpWebResponse res = (HttpWebResponse)req.GetResponse();
 105:          StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.Default);
 106:          string strResult = sr.ReadToEnd();
 107:          sr.Close();
 108:          return strResult;
 109:      }
 110:   
 111:      #endregion
 112:   
 113:      #region  HttpWebRequest
 114:   
 115:      private static CookieContainer cookie = new CookieContainer();
 116:      private static string contentType = "application/x-www-form-urlencoded";
 117:      private static string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
 118:      private static string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
 119:   
 120:      public static string GetHtmlEx(string url)
 121:      {
 122:          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 123:          request.UserAgent = userAgent;
 124:          request.ContentType = contentType;
 125:          request.CookieContainer = cookie;
 126:          request.Accept = accept;
 127:          request.Method = "get";
 128:   
 129:          WebResponse response = request.GetResponse();
 130:          Stream responseStream = response.GetResponseStream();
 131:          Encoding encoding = null;
 132:          for (int i = 0; i < response.Headers.Count; i++)
 133:          {
 134:              Match m = Regex.Match(response.Headers[i].ToString(), "(?i)(?<=charset=)[^ ]+");
 135:              if (!m.Success) continue;
 136:              encoding = Encoding.GetEncoding(m.Value);
 137:              break;
 138:          }
 139:          StreamReader reader = new StreamReader(responseStream, encoding);
 140:          String html = reader.ReadToEnd();
 141:          response.Close();
 142:   
 143:          return html;
 144:      }
 145:   
 146:      #endregion
 147:   
 148:      #region  WebClient
 149:      public static string DownloadData(string url)
 150:      {
 151:          System.Net.WebClient wc = new System.Net.WebClient();
 152:          Byte[] pageData = wc.DownloadData(url);
 153:          string s = System.Text.Encoding.Default.GetString(pageData);
 154:          return s;
 155:      }
 156:      #endregion
 157:   
 158:      #region  获取页面信息,有证书时返回True
 159:      /// <summary>
 160:      /// 传入URL返回网页的html代码
 161:      /// </summary>
 162:      /// <param name="Url">URL</param>
 163:      /// <returns></returns>
 164:      public string GetUrltoHtml(string Url)
 165:      {
 166:          StringBuilder content = new StringBuilder();
 167:          try
 168:          {
 169:              // 与指定URL创建HTTP请求
 170:              ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证
 171:   
 172:              HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
 173:              request.KeepAlive = false;
 174:              request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8; .NET4.0C; .NET4.0E)";
 175:              request.Method = "GET";
 176:              request.Accept = "*/*";
 177:   
 178:              //创建证书文件
 179:              System.Security.Cryptography.X509Certificates.X509Certificate objx509 = new System.Security.Cryptography.X509Certificates.X509Certificate(System.Windows.Forms.Application.StartupPath + "\\123.cer");
 180:   
 181:              //添加到请求里
 182:              request.ClientCertificates.Add(objx509);
 183:   
 184:              HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 185:              // 获取对应HTTP请求的响应
 186:              // 获取响应流
 187:              Stream responseStream = response.GetResponseStream();
 188:              // 对接响应流(以"GBK"字符集)
 189:              StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("GBK"));
 190:              // 开始读取数据
 191:              Char[] sReaderBuffer = new Char[256];
 192:              int count = sReader.Read(sReaderBuffer, 0, 256);
 193:              while (count > 0)
 194:              {
 195:                  String tempStr = new String(sReaderBuffer, 0, count);
 196:                  content.Append(tempStr);
 197:                  count = sReader.Read(sReaderBuffer, 0, 256);
 198:              }
 199:              // 读取结束
 200:              sReader.Close();
 201:          }
 202:          catch (Exception)
 203:          {
 204:              content = new StringBuilder("Runtime Error");
 205:          }
 206:   
 207:          return content.ToString();
 208:      }
 209:      //回调验证证书问题
 210:      public bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors)
 211:      {   // 总是接受    
 212:          return true;
 213:      }
 214:   
 215:      #endregion
 216:   
 217:  }
 218:   
 219:  //最近在做数据采集工作,顺便总结一下几种请求方式。呵呵,我自己懒的写字,就给出几个网上比较经典的程序吧。
 220:  public class RequestWeb
 221:  {
 222:      private readonly static int TIMEOUT = 15000;
 223:      private CookieContainer _cookieCon = new CookieContainer();
 224:      private CredentialCache _credentials;
 225:   
 226:      /// <summary>   
 227:      /// 通过url请求数据   
 228:      /// </summary>   
 229:      /// <param name="url">被请求页面的url</param>   
 230:      /// <param name="proxyServer">代理服务器</param>   
 231:      /// <returns>返回页面内容</returns>   
 232:      public string GetPageContent(string url, string proxyServer)
 233:      {
 234:          StringBuilder ret = new StringBuilder("");
 235:          HttpWebResponse rsp = null;
 236:   
 237:          try
 238:          {
 239:              Uri uri = new Uri(url);
 240:              HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
 241:              if (!string.IsNullOrEmpty(proxyServer))
 242:              {
 243:                  req.Proxy = new WebProxy(proxyServer);
 244:              }
 245:              req.CookieContainer = this._cookieCon;
 246:              req.Headers.Add("Accept-Language: zh-cn");
 247:              req.AllowAutoRedirect = true;
 248:              req.Timeout = TIMEOUT;
 249:   
 250:              if (this._credentials != null)
 251:              {
 252:                  req.PreAuthenticate = true;
 253:                  req.Credentials = this._credentials;
 254:              }
 255:              rsp = (HttpWebResponse)req.GetResponse();
 256:   
 257:              Stream rspStream = rsp.GetResponseStream();
 258:              StreamReader sr = new StreamReader(rspStream, System.Text.Encoding.Default);
 259:   
 260:              //获取数据   
 261:              Char[] read = new Char[256];
 262:              int count = sr.Read(read, 0, 256);
 263:              while (count > 0)
 264:              {
 265:                  ret.Append(read, 0, count);
 266:                  count = sr.Read(read, 0, 256);
 267:              }
 268:          }
 269:          catch (Exception e)
 270:          {
 271:              ret.Append(e.Message);
 272:          }
 273:          finally
 274:          {
 275:              if (rsp != null)
 276:              {
 277:                  rsp.Close();
 278:              }
 279:          }
 280:          return ret.ToString();
 281:      }
 282:   
 283:   
 284:      /// <summary>   
 285:      /// 通过url请求数据(Post方法)   
 286:      /// </summary>   
 287:      /// <param name="url">被请求页面的url</param>   
 288:      /// <param name="param">POST的内容</param>   
 289:      /// <param name="proxyServer">代理</param>   
 290:      /// <returns>返回页面内容</returns>   
 291:      public string GetPageContent(string url, string param, string proxyServer)
 292:      {
 293:          StringBuilder ret = new StringBuilder("");
 294:          HttpWebResponse rsp = null;
 295:   
 296:          try
 297:          {
 298:              Uri uri = new Uri(url);
 299:              HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
 300:              if (!string.IsNullOrEmpty(proxyServer))
 301:              {
 302:                  req.Proxy = new WebProxy(proxyServer);
 303:              }
 304:              req.Method = "POST";
 305:              req.ContentType = "application/x-www-form-urlencoded";
 306:              req.Headers.Add("Accept-Language: zh-cn");
 307:              req.CookieContainer = _cookieCon;
 308:              req.Timeout = TIMEOUT;
 309:              req.AllowAutoRedirect = true;
 310:              if (_credentials != null)
 311:              {
 312:                  req.PreAuthenticate = true;
 313:                  req.Credentials = _credentials;
 314:              }
 315:   
 316:              //传入POST参数的分析   
 317:              if (param != null)
 318:              {
 319:                  string temp = EncodeParams(param, System.Text.Encoding.Default);
 320:                  byte[] bytes = Encoding.UTF8.GetBytes(temp);
 321:                  req.ContentLength = bytes.Length;
 322:                  Stream rspStream = req.GetRequestStream();
 323:                  rspStream.Write(bytes, 0, bytes.Length);
 324:                  rspStream.Close();
 325:              }
 326:              else
 327:              {
 328:                  req.ContentLength = 0;
 329:              }
 330:   
 331:              //取得请求后返回的的数据   
 332:              rsp = (HttpWebResponse)(req.GetResponse());
 333:              Stream ReceiveStream = rsp.GetResponseStream();
 334:              StreamReader sr = new StreamReader(ReceiveStream, System.Text.Encoding.Default);
 335:   
 336:              Char[] read = new Char[256];
 337:              int count = sr.Read(read, 0, 256);
 338:              while (count > 0)
 339:              {
 340:                  ret.Append(read, 0, count);
 341:                  count = sr.Read(read, 0, 256);
 342:              }
 343:          }
 344:          //catch (Exception e)   
 345:          //{   
 346:          //    string err = e.ToString();   
 347:          //}   
 348:          finally
 349:          {
 350:              if (rsp != null)
 351:              {
 352:                  rsp.Close();
 353:              }
 354:          }
 355:          return ret.ToString();
 356:      }
 357:   
 358:      /// <summary>   
 359:      /// 通过传入的url请求文件数据   
 360:      /// </summary>   
 361:      /// <param name="url">图片的URL</param>   
 362:      /// <param name="ProxyServer">代理服务器</param>   
 363:      /// <returns>图片内容</returns>   
 364:      public byte[] GetFile(string url, string proxyServer)
 365:      {
 366:          WebResponse rsp = null;
 367:          byte[] retBytes = null;
 368:   
 369:          try
 370:          {
 371:              Uri uri = new Uri(url);
 372:              WebRequest req = WebRequest.Create(uri);
 373:   
 374:              rsp = req.GetResponse();
 375:              Stream stream = rsp.GetResponseStream();
 376:   
 377:              if (!string.IsNullOrEmpty(proxyServer))
 378:              {
 379:                  req.Proxy = new WebProxy(proxyServer);
 380:              }
 381:   
 382:              using (MemoryStream ms = new MemoryStream())
 383:              {
 384:                  int b;
 385:                  while ((b = stream.ReadByte()) != -1)
 386:                  {
 387:                      ms.WriteByte((byte)b);
 388:                  }
 389:                  retBytes = ms.ToArray();
 390:              }
 391:          }
 392:          catch (Exception ex)
 393:          {
 394:              retBytes = null;
 395:          }
 396:          finally
 397:          {
 398:              if (rsp != null)
 399:              {
 400:                  rsp.Close();
 401:              }
 402:          }
 403:          return retBytes;
 404:      }
 405:   
 406:      private string EncodeParams(string param, Encoding enc)
 407:      {
 408:          StringBuilder ret = new StringBuilder();
 409:          char[] reserved = { '?', '=', '&', '%', '+' };
 410:   
 411:          if (param != null)
 412:          {
 413:              int i = 0, j;
 414:              while (i < param.Length)
 415:              {
 416:                  j = param.IndexOfAny(reserved, i);
 417:                  if (j == -1)
 418:                  {
 419:                      ret.Append(HttpUtility.UrlEncode(param.Substring(i, param.Length - i), enc));
 420:                      break;
 421:                  }
 422:                  ret.Append(HttpUtility.UrlEncode(param.Substring(i, j - i), enc));
 423:                  ret.Append(param.Substring(j, 1));
 424:                  i = j + 1;
 425:              }
 426:          }
 427:          return ret.ToString();
 428:      }
 429:  }
原文地址:https://www.cnblogs.com/hdl217/p/2034048.html