文档章节

HttpHelper

东风125
 东风125
发布于 2015/12/08 19:58
字数 1208
阅读 134
收藏 7

行业解决方案、产品招募中!想赚钱就来传!>>>

 using System;
 using System.Collections.Generic;
 using System.Collections.Specialized;
 using System.IO;
 using System.IO.Compression;
 using System.Linq;
 using System.Net;
 using System.Net.Security;
 using System.Security.Cryptography.X509Certificates;
 using System.Text;
 using System.Text.RegularExpressions;
 using System.Collections;
 using HtmlAgilityPack;
 
 namespace XXX.Common.Helper
 {
     public class HttpHelper
     {
         public const string CharsetReg = @"(meta.*?charset=""?(?<Charset>[^\s""'>]+)""?)|(xml.*?encoding=""?(?<Charset>[^\s"">]+)""?)";
 
         /// <summary>
         /// 获取网页的内容
         /// </summary>
         /// <param name="url">Url</param>
         /// <param name="postData">Post的信息</param>
         /// <param name="cookies">Cookies</param>
         /// <param name="userAgent">浏览器标识</param>
         /// <param name="referer">来源页</param>
         /// <param name="cookiesDomain">Cookies的Domian参数,配合cookies使用;为空则取url的Host</param>
         /// <param name="encode">编码方式,用于解析html</param>
         /// <returns></returns>
         public static string GetHttpContent(string url, string postData = null, CookieContainer cookies = null, string userAgent = "", string referer = "", string cookiesDomain = "", Encoding encode = null)
         {
             try
             {
                 HttpWebResponse httpResponse = null;
                 if (!string.IsNullOrWhiteSpace(postData))
                     httpResponse = CreatePostHttpResponse(url, postData, cookies: cookies, userAgent: userAgent, referer: referer);
                 else
                     httpResponse = CreateGetHttpResponse(url, cookies: cookies, userAgent: userAgent, referer: referer);
 
                 #region 根据Html头判断
                 string Content = null;
                 //缓冲区长度
                 const int N_CacheLength = 10000;
                 //头部预读取缓冲区,字节形式
                 var bytes = new List<byte>();
                 int count = 0;
                 //头部预读取缓冲区,字符串
                 String cache = string.Empty;
 
                 //创建流对象并解码
                 Stream ResponseStream;
                 switch (httpResponse.ContentEncoding.ToUpperInvariant())
                 {
                     case "GZIP":
                         ResponseStream = new GZipStream(
                             httpResponse.GetResponseStream(), CompressionMode.Decompress);
                         break;
                     case "DEFLATE":
                         ResponseStream = new DeflateStream(
                             httpResponse.GetResponseStream(), CompressionMode.Decompress);
                         break;
                     default:
                         ResponseStream = httpResponse.GetResponseStream();
                         break;
                 }
 
                 try
                 {
                     while (
                         !(cache.EndsWith("</head>", StringComparison.OrdinalIgnoreCase)
                           || count >= N_CacheLength))
                     {
                         var b = (byte)ResponseStream.ReadByte();
                         if (b < 0) //end of stream
                         {
                             break;
                         }
                         bytes.Add(b);
 
                         count++;
                         cache += (char)b;
                     }
 
 
                     if (encode == null)
                     {
                         try
                         {
                             if (httpResponse.CharacterSet == "ISO-8859-1" || httpResponse.CharacterSet == "zh-cn")
                             {
                                 Match match = Regex.Match(cache, CharsetReg, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                 if (match.Success)
                                 {
                                     try
                                     {
                                         string charset = match.Groups["Charset"].Value;
                                         encode = Encoding.GetEncoding(charset);
                                     }
                                     catch { }
                                 }
                                 else
                                     encode = Encoding.GetEncoding("GB2312");
                             }
                             else
                                 encode = Encoding.GetEncoding(httpResponse.CharacterSet);
                         }
                         catch { }
                     }
 
                     //缓冲字节重新编码,然后再把流读完
                     var Reader = new StreamReader(ResponseStream, encode);
                     Content = encode.GetString(bytes.ToArray(), 0, count) + Reader.ReadToEnd();
                     Reader.Close();
                 }
                 catch (Exception ex)
                 {
                     return ex.ToString();
                 }
                 finally
                 {
                     httpResponse.Close();
                 }
                 #endregion 根据Html头判断
 
                 //获取返回的Cookies,支持httponly
                 if (string.IsNullOrWhiteSpace(cookiesDomain))
                     cookiesDomain = httpResponse.ResponseUri.Host;
 
                 cookies = new CookieContainer();
                 CookieCollection httpHeaderCookies = SetCookie(httpResponse, cookiesDomain);
                 cookies.Add(httpHeaderCookies ?? httpResponse.Cookies);
 
                 return Content;
             }
             catch
             {
                 return string.Empty;
             }
         }
 
 
         /// <summary>
         /// 创建GET方式的HTTP请求 
         /// </summary>
         /// <param name="url"></param>
         /// <param name="timeout"></param>
         /// <param name="userAgent"></param>
         /// <param name="cookies"></param>
         /// <param name="referer"></param>
         /// <returns></returns>
         public static HttpWebResponse CreateGetHttpResponse(string url, int timeout = 60000, string userAgent = "", CookieContainer cookies = null, string referer = "")
         {
             HttpWebRequest request = null;
             if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
             {
                 //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                 request = WebRequest.Create(url) as HttpWebRequest;
                 //request.ProtocolVersion = HttpVersion.Version10;    //http版本,默认是1.1,这里设置为1.0
             }
             else
             {
                 request = WebRequest.Create(url) as HttpWebRequest;
             }
 
             request.Referer = referer;
             request.Method = "GET";
 
             //设置代理UserAgent和超时
             if (string.IsNullOrWhiteSpace(userAgent))
                 userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36";
 
             request.UserAgent = userAgent;
             request.Timeout = timeout;
             request.KeepAlive = true;
             request.AllowAutoRedirect = true;
 
             if (cookies == null)
                 cookies = new CookieContainer();
             request.CookieContainer = cookies;
 
             return request.GetResponse() as HttpWebResponse;
         }
 
         /// <summary>
         /// 创建POST方式的HTTP请求
         /// </summary>
         /// <param name="url"></param>
         /// <param name="postData"></param>
         /// <param name="timeout"></param>
         /// <param name="userAgent"></param>
         /// <param name="cookies"></param>
         /// <param name="referer"></param>
         /// <returns></returns>
         public static HttpWebResponse CreatePostHttpResponse(string url, string postData, int timeout = 60000, string userAgent = "", CookieContainer cookies = null, string referer = "")
         {
             HttpWebRequest request = null;
             //如果是发送HTTPS请求  
             if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
             {
                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                 request = WebRequest.Create(url) as HttpWebRequest;
                 //request.ProtocolVersion = HttpVersion.Version10;
             }
             else
             {
                 request = WebRequest.Create(url) as HttpWebRequest;
             }
             request.Referer = referer;
             request.Method = "POST";
             request.ContentType = "application/x-www-form-urlencoded";
 
             //设置代理UserAgent和超时
             if (string.IsNullOrWhiteSpace(userAgent))
                 request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36";
             else
                 request.UserAgent = userAgent;
             request.Timeout = timeout;
             request.KeepAlive = true;
             request.AllowAutoRedirect = true;
 
             if (cookies == null)
                 cookies = new CookieContainer();
             request.CookieContainer = cookies;
 
             //发送POST数据  
             if (!string.IsNullOrWhiteSpace(postData))
             {
                 byte[] data = Encoding.UTF8.GetBytes(postData);
                 request.ContentLength = data.Length;
                 using (Stream stream = request.GetRequestStream())
                 {
                     stream.Write(data, 0, data.Length);
                 }
             }
             //string[] values = request.Headers.GetValues("Content-Type");
             return request.GetResponse() as HttpWebResponse;
         }
 
         /// <summary>
         /// 验证证书
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="certificate"></param>
         /// <param name="chain"></param>
         /// <param name="errors"></param>
         /// <returns>是否验证通过</returns>
         private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
         {
             if (errors == SslPolicyErrors.None)
                 return true;
             return false;
         }
 
         /// <summary>
         /// 根据response中头部的set-cookie对request中的cookie进行设置
         /// </summary>
         /// <param name="setCookie">The set cookie.</param>
         /// <param name="defaultDomain">The default domain.</param>
         /// <returns></returns>
         private static CookieCollection SetCookie(HttpWebResponse response, string defaultDomain)
         {
             try
             {
                 string[] setCookie = response.Headers.GetValues("Set-Cookie");
 
                 // there is bug in it,the datetime in "set-cookie" will be sepreated in two pieces.
                 List<string> a = new List<string>(setCookie);
                 for (int i = setCookie.Length - 1; i > 0; i--)
                 {
                     if (a[i].Substring(a[i].Length - 3) == "GMT")
                     {
                         a[i - 1] = a[i - 1] + ", " + a[i];
                         a.RemoveAt(i);
                         i--;
                     }
                 }
                 setCookie = a.ToArray<string>();
                 CookieCollection cookies = new CookieCollection();
                 foreach (string str in setCookie)
                 {
                     NameValueCollection hs = new NameValueCollection();
                     foreach (string i in str.Split(';'))
                     {
                         int index = i.IndexOf("=");
                         if (index > 0)
                             hs.Add(i.Substring(0, index).Trim(), i.Substring(index + 1).Trim());
                         else
                             switch (i)
                             {
                                 case "HttpOnly":
                                     hs.Add("HttpOnly", "True");
                                     break;
                                 case "Secure":
                                     hs.Add("Secure", "True");
                                     break;
                             }
                     }
                     Cookie ck = new Cookie();
                     foreach (string Key in hs.AllKeys)
                     {
                         switch (Key.ToLower().Trim())
                         {
                             case "path":
                                 ck.Path = hs[Key];
                                 break;
                             case "expires":
                                 ck.Expires = DateTime.Parse(hs[Key]);
                                 break;
                             case "domain":
                                 ck.Domain = hs[Key];
                                 break;
                             case "httpOnly":
                                 ck.HttpOnly = true;
                                 break;
                             case "secure":
                                 ck.Secure = true;
                                 break;
                             default:
                                 ck.Name = Key;
                                 ck.Value = hs[Key];
                                 break;
                         }
                     }
                     if (ck.Domain == "") ck.Domain = defaultDomain;
                     if (ck.Name != "") cookies.Add(ck);
                 }
                 return cookies;
             }
             catch
             {
                 return null;
             }
         }
 
         /// <summary>
         /// 遍历CookieContainer
         /// </summary>
         /// <param name="cookieContainer"></param>
         /// <returns>List of cookie</returns>
         public static Dictionary<string, string> GetAllCookies(CookieContainer cookieContainer)
         {
             Dictionary<string, string> cookies = new Dictionary<string, string>();
 
             Hashtable table = (Hashtable)cookieContainer.GetType().InvokeMember("m_domainTable",
                 System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
                 System.Reflection.BindingFlags.Instance, null, cookieContainer, new object[] { });
 
             foreach (string pathList in table.Keys)
             {
                 StringBuilder _cookie = new StringBuilder();
                 SortedList cookieColList = (SortedList)table[pathList].GetType().InvokeMember("m_list",
                     System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                     | System.Reflection.BindingFlags.Instance, null, table[pathList], new object[] { });
                 foreach (CookieCollection colCookies in cookieColList.Values)
                     foreach (Cookie c in colCookies)
                         _cookie.Append(c.Name + "=" + c.Value + ";");
 
                 cookies.Add(pathList, _cookie.ToString().TrimEnd(';'));
             }
             return cookies;
         }
 
         /// <summary>
         /// convert cookies string to CookieContainer
         /// </summary>
         /// <param name="cookies"></param>
         /// <returns></returns>
         public static CookieContainer ConvertToCookieContainer(Dictionary<string, string> cookies)
         {
             CookieContainer cookieContainer = new CookieContainer();
 
             foreach (var cookie in cookies)
             {
                 string[] strEachCookParts = cookie.Value.Split(';');
                 int intEachCookPartsCount = strEachCookParts.Length;
 
                 foreach (string strCNameAndCValue in strEachCookParts)
                 {
                     if (!string.IsNullOrEmpty(strCNameAndCValue))
                     {
                         Cookie cookTemp = new Cookie();
                         int firstEqual = strCNameAndCValue.IndexOf("=");
                         string firstName = strCNameAndCValue.Substring(0, firstEqual);
                         string allValue = strCNameAndCValue.Substring(firstEqual + 1, strCNameAndCValue.Length - (firstEqual + 1));
                         cookTemp.Name = firstName;
                         cookTemp.Value = allValue;
                         cookTemp.Path = "/";
                         cookTemp.Domain = cookie.Key;
                         cookieContainer.Add(cookTemp);
                     }
                 }
             }
             return cookieContainer;
         }
 
         public static string BuildPostData(string htmlContent)
         {
             HtmlDocument htmlDoc = new HtmlDocument();
             htmlDoc.LoadHtml(htmlContent);
             //Get the form node collection.
             HtmlNode htmlNode = htmlDoc.DocumentNode.SelectSingleNode("//form");
             HtmlNodeCollection htmlInputs = htmlNode.SelectNodes("//input");
 
             StringBuilder postData = new StringBuilder();
 
             foreach (HtmlNode input in htmlInputs)
             {
                 if(input.Attributes["value"] != null)
                     postData.Append(input.Attributes["name"].Value + "=" + input.Attributes["value"].Value + "&");
             }
             return postData.ToString().TrimEnd('&');
         }
     }
 }
东风125
粉丝 6
博文 73
码字总数 12747
作品 0
朝阳
高级程序员
私信 提问
加载中
此博客有 1 条评论,请先登录后再查看。
android精品游戏连连看整套项目源码

源码介绍: 本项目是一个基于安卓的连连看游戏项目源码(联机在线连连看),带有一个用心设计过的毕业设计PPT演示文档和一个word文档。应用UI非常美观,本项目包括连连看安卓客户端源码+asp....

YXKFW
2015/12/05
92
0
淘宝API开发系列---淘宝API的测试及使用2

继续前面一篇随笔《淘宝API开发系列---淘宝API的测试及使用》,来继续介绍淘宝API的具体代码开发部分,上篇主要是介绍淘宝SDK开发的一些流程及必备的信息,以及掌握如何学会利用API文档、淘宝...

长平狐
2012/08/22
191
0
如何使用C#实现网易博客中圈子用户数据的采集

新浪博客,网易博客,都是博客中的佼佼者,其中网易提供的圈子信息,更胜一筹,使得一般用户能够通过访问圈子进入相关的群组,或者获取相关圈子用户的信息等,以实现各种精准营销的目的。虽然...

长平狐
2012/06/11
211
0
厚积薄发,丰富的公用类库积累,助你高效进行系统开发(8)----非对称加密、BASE64加密、MD5等常用加密处理

俗话说,一个好汉十个帮,众人拾柴火焰高等都说明一个道理,有更多的资源,更丰富的积累,都是助你走向成功,走向顶峰的推动力。 本篇继续继续整理优化已有的共用类库,并继续发表随笔介绍公...

长平狐
2012/06/11
236
0
Http 请求框架--httphelper

轻量级Http,HttpClient,HttpHelper请求框架。 清晰明了的请求接口描述,灵活的扩展机制。 支持同步调用; 支持异步调用,异步回调; 支持JSON自动转换为指定类型; 支持自定义输入参数验证;...

AlexGaoZ
2016/01/04
7.7K
2

没有更多内容

加载失败,请刷新页面

加载更多

鼠年吉祥,新年快乐

今天是大年初一,很高兴在过去一年中有您的陪伴,希望大家在新的一年中平安健康,一切顺利,加油。 邓飞 202001250539 于后园爷爷家 本文分享自微信公众号 - 育种数据分析之放飞自我(R-bre...

育种数据分析之放飞自
01/25
0
0
不烧脑、不耗时、全免费,带你0基础学Python

文末有福利 Python是人工智能的未来。 最近,电气和电子工程师协会( IEEE)发布了顶级编程语言交互排行榜:Python高居首位。 而且随着大数据和人工智能的发展,Python受到了越来越多程序员的...

kunjian
今天
11
0
R语言入门系列之一

写在前面 计算机语言的学习并不困难,关键是一定要由浅入深的实际操作练习。也许最开始的比较简单,学习者一带而过没有实际操作,之后的进一步学习很可能会陷入不知所云的困境,实际操作所带...

SYSU星空
2019/02/17
0
0
Istio-本地运行

概述 基于上一篇 Istio1.6-二进制编译和本地运行 但集中在 pilot-discovery 和 envoy(pilot-agent 大部分功能仅作为 envoy 的 watchdog,略过) NOTE: 以下的描述,相对路径都基于目录 /g...

深蓝苹果
50分钟前
9
0
基于Linux、C、JSON、Socket的编程实例(附代码)

点击上方「嵌入式大杂烩」,选择「置顶公众号」第一时间阅读编程笔记! 一、前言 之前在学习socket编程的时候有分享一个基于控制台的简易天气客户端的实现,当时提供的是window下的代码,最近...

学以解忧
2019/10/29
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部