架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

搜索
查看: 21728|回复: 1

[资料] 一个特别不错的http请求类

[复制链接]
发表于 2016-6-5 15:50:40 | 显示全部楼层 |阅读模式
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.IO;
  6. using System.IO.Compression;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Security;
  10. using System.Security.Cryptography.X509Certificates;
  11. using System.Text;
  12. using System.Text.RegularExpressions;

  13. namespace aaa
  14. {
  15.     public class ResponseModel
  16.     {
  17.         private WebHeaderCollection header;
  18.         /// <summary>
  19.         /// 返回的头部信息集合
  20.         /// </summary>
  21.         public WebHeaderCollection Header
  22.         {
  23.             get { return header; }
  24.             set { header = value; }
  25.         }
  26.         private string html;
  27.         /// <summary>
  28.         /// 返回的文本内容
  29.         /// </summary>
  30.         public string Html
  31.         {
  32.             get { return html; }
  33.             set { html = value; }
  34.         }
  35.         private Stream stream;
  36.         /// <summary>
  37.         /// 返回的流内容
  38.         /// </summary>
  39.         public Stream Stream
  40.         {
  41.             get { return stream; }
  42.             set { stream = value; }
  43.         }

  44.     }
  45.     public class HttpHelper
  46.     {
  47.         private string accept = "application/json,text/javascrip{过滤}t,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
  48.         private System.Net.CookieContainer cc = new System.Net.CookieContainer();
  49.         private string contentType = "application/x-www-form-urlencoded";

  50.         private int timeOut = 30000;
  51.         public NameValueCollection Heads = new NameValueCollection();
  52.         private bool AllowAutoRedirect = false;
  53.         bool needReset = false;
  54.         private System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");

  55.         public IWebProxy Proxy;
  56.         private string[] userAgents = new string[] { "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)", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0" };

  57.         private string userAgent
  58.         {
  59.             get
  60.             {
  61.                 return this.userAgents[new Random().Next(0, this.userAgents.Length)];
  62.             }
  63.         }


  64.         /// <summary>
  65.         /// 设置下一次请求为自动重定向
  66.         /// </summary>
  67.         /// <param name="value"></param>
  68.         public void SetAllowAutoRedirectOneTime(bool value)
  69.         {
  70.             AllowAutoRedirect = value;
  71.             needReset = true;
  72.         }

  73.         /// <summary>
  74.         /// 网页访问
  75.         /// </summary>
  76.         /// <param name="url">请求地址</param>
  77.         /// <param name="isPost">是否Post</param>
  78.         /// <param name="postData">Post数据内容</param>
  79.         /// <param name="retType">返回类型0为文本,1为Stream</param>
  80.         /// <param name="cookieContainer">cookie</param>
  81.         /// <param name="refurl">Referer</param>
  82.         /// <param name="_contentType">contentType</param>
  83.         /// <param name="headers">请求头</param>
  84.         /// <returns></returns>
  85.         public ResponseModel HttpVisit(string url, bool isPost = false, string postData = null, int retType = 0, System.Net.CookieContainer cookieContainer = null, string refurl = null, string _contentType = null, NameValueCollection headers = null)
  86.         {
  87.             if (cookieContainer == null)
  88.             {
  89.                 cookieContainer = this.cc;
  90.             }

  91.             if (!isPost)
  92.             {
  93.                 return GetHtml(url, refurl, cookieContainer, _contentType, headers, retType);
  94.             }


  95.             ResponseModel model = new ResponseModel();

  96.             ServicePointManager.Expect100Continue = true;

  97.             ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

  98.             HttpWebRequest request = null;
  99.             HttpWebResponse response = null;
  100.             try
  101.             {
  102.                 byte[] bytes = System.Text.Encoding.Default.GetBytes(postData);
  103.                 request = (HttpWebRequest)WebRequest.Create(url);
  104.                 if (this.Proxy != null) request.Proxy = this.Proxy;
  105.                 request.CookieContainer = cookieContainer;
  106.                 request.Timeout = timeOut;
  107.                 if (string.IsNullOrEmpty(_contentType))
  108.                 {
  109.                     request.ContentType = this.contentType;
  110.                 }
  111.                 else
  112.                 {
  113.                     request.ContentType = _contentType;
  114.                 }

  115.                 if (string.IsNullOrEmpty(refurl))
  116.                 {
  117.                     request.Referer = url;
  118.                 }
  119.                 else
  120.                 {
  121.                     request.Referer = refurl;
  122.                 }


  123.                 request.AllowAutoRedirect = AllowAutoRedirect;
  124.                 request.Accept = this.accept;
  125.                 request.UserAgent = this.userAgent;

  126.                 if (headers != null)
  127.                 {
  128.                     request.Headers.Add(Heads);
  129.                     request.Headers.Add(headers);
  130.                 }
  131.                 else
  132.                 {
  133.                     request.Headers.Add(Heads);
  134.                 }


  135.                 request.Method = isPost ? "POST" : "GET";
  136.                 request.ContentLength = bytes.Length;


  137.                 Stream requestStream = request.GetRequestStream();
  138.                 requestStream.Write(bytes, 0, bytes.Length);
  139.                 requestStream.Close();


  140.                 if (retType == 1)
  141.                 {
  142.                     response = (HttpWebResponse)request.GetResponse();

  143.                     model.Header = response.Headers;

  144.                     Stream responseStream = response.GetResponseStream();

  145.                     if (response.Cookies.Count > 0)
  146.                     {
  147.                         this.cc.Add(response.Cookies);
  148.                     }

  149.                     model.Stream = responseStream;
  150.                     return model;

  151.                 }


  152.                 string str = string.Empty;
  153.                 response = (HttpWebResponse)request.GetResponse();

  154.                 model.Header = response.Headers;

  155.                 string encoding = "utf-8";

  156.                 if (!string.IsNullOrEmpty(response.CharacterSet))
  157.                 {
  158.                     encoding = response.CharacterSet.ToLower();
  159.                 }
  160.                 else
  161.                 {
  162.                     encoding = this.encoding.HeaderName;
  163.                 }

  164.                 if (response.ContentEncoding.ToLower().Contains("gzip"))
  165.                 {

  166.                     using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
  167.                     {
  168.                         using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
  169.                         {

  170.                             str = reader.ReadToEnd();
  171.                         }
  172.                     }
  173.                 }
  174.                 else if (response.ContentEncoding.ToLower().Contains("deflate"))
  175.                 {
  176.                     using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
  177.                     {
  178.                         using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
  179.                         {

  180.                             str = reader.ReadToEnd();
  181.                         }

  182.                     }
  183.                 }
  184.                 else
  185.                 {
  186.                     using (Stream stream = response.GetResponseStream())
  187.                     {
  188.                         using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
  189.                         {

  190.                             str = reader.ReadToEnd();
  191.                         }
  192.                     }
  193.                 }


  194.                 request.Abort();
  195.                 response.Close();
  196.                 request.Abort();
  197.                 if (response.Cookies.Count > 0)
  198.                 {
  199.                     this.cc.Add(response.Cookies);
  200.                 }
  201.                 model.Html = str;
  202.                 return model;
  203.             }
  204.             catch (Exception ex)
  205.             {
  206.                 if (request != null) request.Abort();
  207.                 if (response != null)
  208.                 {
  209.                     response.Close();

  210.                     return new ResponseModel() { Html = ex.Message, Header = response.Headers };
  211.                 }
  212.                 return new ResponseModel() { Html = ex.Message };
  213.             }
  214.             finally
  215.             {
  216.                 if (needReset)
  217.                 {
  218.                     AllowAutoRedirect = false;
  219.                     needReset = false;
  220.                 }
  221.             }
  222.         }
  223.         /// <summary>
  224.         /// 清理string类型Cookie.剔除无用项返回结果为null时遇见错误.
  225.         /// </summary>
  226.         /// <param name="Cookies"></param>
  227.         /// <returns></returns>
  228.         public CookieCollection ClearCookie(string Cookies)
  229.         {
  230.             try
  231.             {
  232.                 CookieCollection cookies = new CookieCollection();
  233.                 string rStr = string.Empty;
  234.                 Cookies = Cookies.Replace(";", "; ");
  235.                 Regex r = new Regex("(?<=,)(?<cookie>[^ ]+=(?!deleted;)[^;]+);");
  236.                 MatchCollection ms = r.Matches("," + Cookies);
  237.                 foreach (Match m in ms)
  238.                 {
  239.                     string[] cookie = m.Groups["cookie"].Value.Split('=');

  240.                     if (cookie.Length > 1)
  241.                         cookies.Add(new Cookie(cookie[0], cookie[1]));

  242.                 }
  243.                 return cookies;
  244.             }
  245.             catch
  246.             {
  247.                 return new CookieCollection();
  248.             }
  249.         }

  250.         private ResponseModel GetHtml(string url, string refurl = null, System.Net.CookieContainer cookieContainer = null, string _contentType = "", NameValueCollection headers = null, int retType = 1)
  251.         {
  252.             if (cookieContainer == null)
  253.             {
  254.                 cookieContainer = this.cc;
  255.             }

  256.             ResponseModel model = new ResponseModel();

  257.             ServicePointManager.Expect100Continue = true;

  258.             ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

  259.             HttpWebRequest request = null;
  260.             HttpWebResponse response = null;
  261.             try
  262.             {
  263.                 request = (HttpWebRequest)WebRequest.Create(url);
  264.                 if (this.Proxy != null) request.Proxy = this.Proxy;
  265.                 request.CookieContainer = cookieContainer;
  266.                 request.Timeout = timeOut;
  267.                 if (string.IsNullOrEmpty(_contentType))
  268.                 {
  269.                     request.ContentType = this.contentType;
  270.                 }
  271.                 else
  272.                 {
  273.                     request.ContentType = _contentType;
  274.                 }

  275.                 if (string.IsNullOrEmpty(refurl))
  276.                 {
  277.                     request.Referer = url;
  278.                 }
  279.                 else
  280.                 {
  281.                     request.Referer = refurl;
  282.                 }


  283.                 request.AllowAutoRedirect = AllowAutoRedirect;
  284.                 request.Accept = this.accept;
  285.                 request.UserAgent = this.userAgent;

  286.                 if (headers != null)
  287.                 {
  288.                     request.Headers.Add(Heads);
  289.                     request.Headers.Add(headers);
  290.                 }
  291.                 else
  292.                 {
  293.                     request.Headers.Add(Heads);
  294.                 }

  295.                 request.Method = "GET";


  296.                 if (retType == 1)
  297.                 {
  298.                     response = (HttpWebResponse)request.GetResponse();

  299.                     model.Header = response.Headers;

  300.                     Stream responseStream = response.GetResponseStream();

  301.                     if (response.Cookies.Count > 0)
  302.                     {
  303.                         this.cc.Add(response.Cookies);
  304.                     }

  305.                     model.Stream = responseStream;

  306.                     return model;

  307.                 }

  308.                 string str = string.Empty;
  309.                 response = (HttpWebResponse)request.GetResponse();

  310.                 model.Header = response.Headers;

  311.                 string encoding = "utf-8";

  312.                 if (!string.IsNullOrEmpty(response.CharacterSet))
  313.                 {
  314.                     encoding = response.CharacterSet.ToLower();
  315.                 }
  316.                 else
  317.                 {
  318.                     encoding = this.encoding.HeaderName;
  319.                 }

  320.                 if (response.ContentEncoding.ToLower().Contains("gzip"))
  321.                 {

  322.                     using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
  323.                     {
  324.                         using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
  325.                         {

  326.                             str = reader.ReadToEnd();
  327.                         }
  328.                     }
  329.                 }
  330.                 else if (response.ContentEncoding.ToLower().Contains("deflate"))
  331.                 {
  332.                     using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
  333.                     {
  334.                         using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
  335.                         {

  336.                             str = reader.ReadToEnd();
  337.                         }

  338.                     }
  339.                 }
  340.                 else
  341.                 {
  342.                     using (Stream stream = response.GetResponseStream())
  343.                     {
  344.                         using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
  345.                         {

  346.                             str = reader.ReadToEnd();
  347.                         }
  348.                     }
  349.                 }

  350.                 if (response.Cookies.Count > 0)
  351.                 {
  352.                     cookieContainer.Add(response.Cookies);
  353.                 }


  354.                 request.Abort();
  355.                 response.Close();

  356.                 model.Html = str;
  357.                 return model;
  358.             }
  359.             catch (Exception ex)
  360.             {
  361.                 if (request != null) request.Abort();
  362.                 if (response != null)
  363.                 {
  364.                     response.Close();

  365.                     return new ResponseModel() { Html = ex.Message, Header = response.Headers };
  366.                 }
  367.                 return new ResponseModel() { Html = ex.Message };
  368.             }
  369.             finally
  370.             {
  371.                 if (needReset)
  372.                 {
  373.                     AllowAutoRedirect = false;
  374.                     needReset = false;
  375.                 }
  376.             }
  377.         }

  378.         private bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  379.         {
  380.             //直接通过HTTPS的证书请求
  381.             return true;
  382.         }

  383.         public Stream GetStream(string url)
  384.         {
  385.             HttpWebRequest request = null;
  386.             HttpWebResponse response = null;
  387.             try
  388.             {
  389.                 request = (HttpWebRequest)WebRequest.Create(url);
  390.                 if (this.Proxy != null) request.Proxy = this.Proxy;
  391.                 request.CookieContainer = this.cc;
  392.                 request.ContentType = this.contentType;
  393.                 //      request.ServicePoint.ConnectionLimit = this.maxTry;
  394.                 request.Timeout = 0x1388;
  395.                 request.Referer = url;
  396.                 request.Accept = this.accept;
  397.                 request.UserAgent = this.userAgent;
  398.                 request.Method = "GET";
  399.                 response = (HttpWebResponse)request.GetResponse();

  400.                 Stream responseStream = response.GetResponseStream();
  401.                 // this.currentTry--;
  402.                 if (response.Cookies.Count > 0)
  403.                 {
  404.                     this.cc.Add(response.Cookies);
  405.                 }
  406.                 return responseStream;
  407.             }
  408.             catch (Exception ex)
  409.             {
  410.                 //   if (this.currentTry <= this.maxTry) this.GetHtml(url, cookieContainer);
  411.                 //   this.currentTry--;
  412.                 if (request != null) request.Abort();
  413.                 if (response != null) response.Close();
  414.                 return null;
  415.             }
  416.         }


  417.         #region String与CookieContainer互转
  418.         /// <summary>
  419.         /// 将String转CookieContainer
  420.         /// </summary>
  421.         /// <param name="url"></param>
  422.         /// <param name="cookie"></param>
  423.         /// <returns></returns>
  424.         public CookieContainer StringToCookie(string url, string cookie)
  425.         {
  426.             string[] arrCookie = cookie.Split(';');
  427.             CookieContainer cookie_container = new CookieContainer();    //加载Cookie
  428.             foreach (string sCookie in arrCookie)
  429.             {
  430.                 if (sCookie.IndexOf("expires") > 0)
  431.                     continue;
  432.                 cookie_container.SetCookies(new Uri(url), sCookie);
  433.             }
  434.             return cookie_container;
  435.         }


  436.         /// <summary>
  437.         /// 将CookieContainer转换为string类型
  438.         /// </summary>
  439.         /// <param name="cc"></param>
  440.         /// <returns></returns>
  441.         public string GetCookieString()
  442.         {
  443.             System.Collections.Generic.List<Cookie> lstCookies = new System.Collections.Generic.List<Cookie>();
  444.             Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
  445.                 System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
  446.                 System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
  447.             StringBuilder sb = new StringBuilder();
  448.             foreach (object pathList in table.Values)
  449.             {
  450.                 SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
  451.                     System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
  452.                     | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
  453.                 foreach (CookieCollection colCookies in lstCookieCol.Values)
  454.                     foreach (Cookie c in colCookies)
  455.                     {
  456.                         sb.Append(c.Name).Append("=").Append(c.Value).Append(";");
  457.                     }
  458.             }
  459.             return sb.ToString();
  460.         }
  461.         #endregion

  462.     }
  463. }
复制代码






上一篇:c#字典The given key was not present in the dictionary
下一篇:“世创优品”加盟赚钱吗?世创优品怎么样?坑死你!!
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
发表于 2016-8-8 14:00:25 | 显示全部楼层
写代码 不打注释的 烧饼
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2026-6-16 00:30

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表