HttpHelper.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4. using System.Net;
  5. using System.Net.Security;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. namespace SCC.Common
  10. {
  11. /// <summary>
  12. /// Http连接操作帮助类
  13. /// </summary>
  14. public class HttpHelper
  15. {
  16. #region 预定义方变量
  17. //默认的编码
  18. private Encoding _encoding = Encoding.Default;
  19. //Post数据编码
  20. private Encoding _postencoding = Encoding.Default;
  21. //HttpWebRequest对象用来发起请求
  22. private HttpWebRequest _request = null;
  23. //获取影响流的数据对象
  24. private HttpWebResponse _response = null;
  25. //设置本地的出口ip和端口
  26. private IPEndPoint _ipEndPoint = null;
  27. #endregion
  28. #region Public
  29. /// <summary>
  30. /// 根据相传入的数据,得到相应页面数据
  31. /// </summary>
  32. /// <param name="item">参数类对象</param>
  33. /// <returns>返回HttpResult类型</returns>
  34. public HttpResult GetHtml(HttpItem item)
  35. {
  36. //返回参数
  37. HttpResult result = new HttpResult();
  38. try
  39. {
  40. //准备参数
  41. SetRequest(item);
  42. }
  43. catch (Exception ex)
  44. {
  45. result.Cookie = string.Empty;
  46. result.Header = null;
  47. result.Html = ex.Message;
  48. result.StatusDescription = "配置参数时出错:" + ex.Message;
  49. //配置参数时出错
  50. return result;
  51. }
  52. try
  53. {
  54. //请求数据
  55. using (_response = (HttpWebResponse)_request.GetResponse())
  56. {
  57. GetData(item, result);
  58. }
  59. }
  60. catch (WebException ex)
  61. {
  62. if (ex.Response != null)
  63. {
  64. using (_response = (HttpWebResponse)ex.Response)
  65. {
  66. GetData(item, result);
  67. }
  68. }
  69. else
  70. {
  71. result.Html = ex.Message;
  72. }
  73. }
  74. catch (Exception ex)
  75. {
  76. result.Html = ex.Message;
  77. }
  78. if (item.IsToLower)
  79. result.Html = result.Html.ToLower();
  80. return result;
  81. }
  82. #endregion
  83. #region GetData
  84. /// <summary>
  85. /// 获取数据的并解析的方法
  86. /// </summary>
  87. /// <param name="item"></param>
  88. /// <param name="result"></param>
  89. private void GetData(HttpItem item, HttpResult result)
  90. {
  91. #region base
  92. //获取StatusCode
  93. result.StatusCode = _response.StatusCode;
  94. //获取StatusDescription
  95. result.StatusDescription = _response.StatusDescription;
  96. //获取最后访问的URl
  97. result.ResponseUri = _response.ResponseUri.ToString();
  98. //获取Headers
  99. result.Header = _response.Headers;
  100. //获取CookieCollection
  101. if (_response.Cookies != null) result.CookieCollection = _response.Cookies;
  102. //获取set-cookie
  103. if (_response.Headers["set-cookie"] != null) result.Cookie = _response.Headers["set-cookie"];
  104. #endregion
  105. #region byte
  106. //处理网页Byte
  107. byte[] responseByte = GetByte();
  108. #endregion
  109. #region Html
  110. if (responseByte != null && responseByte.Length > 0)
  111. {
  112. //设置编码
  113. SetEncoding(item, result, responseByte);
  114. //得到返回的HTML
  115. result.Html = _encoding.GetString(responseByte);
  116. }
  117. else
  118. {
  119. //没有返回任何Html代码
  120. result.Html = string.Empty;
  121. }
  122. #endregion
  123. }
  124. /// <summary>
  125. /// 设置编码
  126. /// </summary>
  127. /// <param name="item">HttpItem</param>
  128. /// <param name="result">HttpResult</param>
  129. /// <param name="responseByte">byte[]</param>
  130. private void SetEncoding(HttpItem item, HttpResult result, byte[] responseByte)
  131. {
  132. //是否返回Byte类型数据
  133. if (item.ResultType == ResultType.Byte) result.ResultByte = responseByte;
  134. //从这里开始我们要无视编码了
  135. if (_encoding == null)
  136. {
  137. Match meta = Regex.Match(Encoding.Default.GetString(responseByte), "<meta[^<]*charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
  138. string c = string.Empty;
  139. if (meta != null && meta.Groups.Count > 0)
  140. {
  141. c = meta.Groups[1].Value.ToLower().Trim();
  142. }
  143. if (c.Length > 2)
  144. {
  145. try
  146. {
  147. _encoding = Encoding.GetEncoding(c.Replace("\"", string.Empty).Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
  148. }
  149. catch
  150. {
  151. _encoding = string.IsNullOrEmpty(_response.CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(_response.CharacterSet);
  152. }
  153. }
  154. else
  155. {
  156. _encoding = string.IsNullOrEmpty(_response.CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(_response.CharacterSet);
  157. }
  158. }
  159. }
  160. /// <summary>
  161. /// 提取网页Byte
  162. /// </summary>
  163. /// <returns></returns>
  164. private byte[] GetByte()
  165. {
  166. byte[] responseByte = null;
  167. MemoryStream stream;
  168. //GZIIP处理
  169. if (_response.ContentEncoding != null && _response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
  170. {
  171. //开始读取流并设置编码方式
  172. stream = GetMemoryStream(new GZipStream(_response.GetResponseStream(), CompressionMode.Decompress));
  173. }
  174. else
  175. {
  176. //开始读取流并设置编码方式
  177. stream = GetMemoryStream(_response.GetResponseStream());
  178. }
  179. //获取Byte
  180. responseByte = stream.ToArray();
  181. stream.Close();
  182. return responseByte;
  183. }
  184. /// <summary>
  185. /// 4.0以下.net版本取数据使用
  186. /// </summary>
  187. /// <param name="streamResponse">流</param>
  188. private MemoryStream GetMemoryStream(Stream streamResponse)
  189. {
  190. MemoryStream stream = new MemoryStream();
  191. int Length = 256;
  192. Byte[] buffer = new Byte[Length];
  193. int bytesRead = streamResponse.Read(buffer, 0, Length);
  194. while (bytesRead > 0)
  195. {
  196. stream.Write(buffer, 0, bytesRead);
  197. bytesRead = streamResponse.Read(buffer, 0, Length);
  198. }
  199. return stream;
  200. }
  201. #endregion
  202. #region SetRequest
  203. /// <summary>
  204. /// 为请求准备参数
  205. /// </summary>
  206. ///<param name="item">参数列表</param>
  207. private void SetRequest(HttpItem item)
  208. {
  209. // 验证证书
  210. SetCer(item);
  211. if (item.IPEndPoint != null)
  212. {
  213. _ipEndPoint = item.IPEndPoint;
  214. //设置本地的出口ip和端口
  215. _request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
  216. }
  217. //设置Header参数
  218. if (item.Header != null && item.Header.Count > 0)
  219. {
  220. foreach (string key in item.Header.AllKeys)
  221. {
  222. _request.Headers.Add(key, item.Header[key]);
  223. }
  224. }
  225. // 设置代理
  226. SetProxy(item);
  227. if (item.ProtocolVersion != null)
  228. {
  229. //获取或设置用于请求的 HTTP 版本
  230. _request.ProtocolVersion = item.ProtocolVersion;
  231. }
  232. //获取或设置一个 System.Boolean 值,该值确定是否使用 100-Continue 行为
  233. _request.ServicePoint.Expect100Continue = item.Expect100Continue;
  234. //请求方式Get或者Post
  235. _request.Method = item.Method;
  236. //请求超时时间
  237. _request.Timeout = item.Timeout;
  238. //是否建立永久链接
  239. _request.KeepAlive = item.KeepAlive;
  240. //写入数据超时时间
  241. _request.ReadWriteTimeout = item.ReadWriteTimeout;
  242. if (item.IfModifiedSince != null)
  243. {
  244. //获取或设置 If-Modified-Since HTTP 标头的值
  245. _request.IfModifiedSince = Convert.ToDateTime(item.IfModifiedSince);
  246. }
  247. //Accept
  248. _request.Accept = item.Accept;
  249. //ContentType返回类型
  250. _request.ContentType = item.ContentType;
  251. //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息
  252. _request.UserAgent = item.UserAgent;
  253. // 编码
  254. _encoding = item.Encoding;
  255. //设置安全凭证
  256. _request.Credentials = item.ICredentials;
  257. //设置Cookie
  258. SetCookie(item);
  259. //来源地址
  260. _request.Referer = item.Referer;
  261. //是否执行跳转功能
  262. _request.AllowAutoRedirect = item.Allowautoredirect;
  263. if (item.MaximumAutomaticRedirections > 0)
  264. {
  265. //获取或设置请求将跟随的重定向的最大数目
  266. _request.MaximumAutomaticRedirections = item.MaximumAutomaticRedirections;
  267. }
  268. //设置Post数据
  269. SetPostData(item);
  270. //设置最大连接
  271. if (item.Connectionlimit > 0)
  272. {
  273. //获取或设置此 System.Net.ServicePoint 对象上允许的最大连接数
  274. _request.ServicePoint.ConnectionLimit = item.Connectionlimit;
  275. }
  276. }
  277. /// <summary>
  278. /// 设置证书
  279. /// </summary>
  280. /// <param name="item"></param>
  281. private void SetCer(HttpItem item)
  282. {
  283. if (!string.IsNullOrEmpty(item.CerPath))
  284. {
  285. //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
  286. ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
  287. //初始化对像,并设置请求的URL地址
  288. _request = (HttpWebRequest)WebRequest.Create(item.Url);
  289. SetCerList(item);
  290. //将证书添加到请求里
  291. _request.ClientCertificates.Add(new X509Certificate(item.CerPath));
  292. }
  293. else
  294. {
  295. //初始化对像,并设置请求的URL地址
  296. _request = (HttpWebRequest)WebRequest.Create(item.Url);
  297. SetCerList(item);
  298. }
  299. }
  300. /// <summary>
  301. /// 设置多个证书
  302. /// </summary>
  303. /// <param name="item"></param>
  304. private void SetCerList(HttpItem item)
  305. {
  306. if (item.ClentCertificates != null && item.ClentCertificates.Count > 0)
  307. {
  308. foreach (X509Certificate c in item.ClentCertificates)
  309. {
  310. _request.ClientCertificates.Add(c);
  311. }
  312. }
  313. }
  314. /// <summary>
  315. /// 设置Cookie
  316. /// </summary>
  317. /// <param name="item">Http参数</param>
  318. private void SetCookie(HttpItem item)
  319. {
  320. if (!string.IsNullOrEmpty(item.Cookie)) _request.Headers[HttpRequestHeader.Cookie] = item.Cookie;
  321. //设置CookieCollection
  322. if (item.ResultCookieType == ResultCookieType.CookieCollection)
  323. {
  324. _request.CookieContainer = new CookieContainer();
  325. if (item.CookieCollection != null && item.CookieCollection.Count > 0)
  326. _request.CookieContainer.Add(item.CookieCollection);
  327. }
  328. }
  329. /// <summary>
  330. /// 设置Post数据
  331. /// </summary>
  332. /// <param name="item">Http参数</param>
  333. private void SetPostData(HttpItem item)
  334. {
  335. //验证在得到结果时是否有传入数据
  336. if (!_request.Method.Trim().ToLower().Contains("get"))
  337. {
  338. if (item.PostEncoding != null)
  339. {
  340. _postencoding = item.PostEncoding;
  341. }
  342. byte[] buffer = null;
  343. //写入Byte类型
  344. if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
  345. {
  346. //验证在得到结果时是否有传入数据
  347. buffer = item.PostdataByte;
  348. }//写入文件
  349. else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrEmpty(item.Postdata))
  350. {
  351. StreamReader r = new StreamReader(item.Postdata, _postencoding);
  352. buffer = _postencoding.GetBytes(r.ReadToEnd());
  353. r.Close();
  354. } //写入字符串
  355. else if (!string.IsNullOrEmpty(item.Postdata))
  356. {
  357. buffer = _postencoding.GetBytes(item.Postdata);
  358. }
  359. if (buffer != null)
  360. {
  361. _request.ContentLength = buffer.Length;
  362. _request.GetRequestStream().Write(buffer, 0, buffer.Length);
  363. }
  364. else
  365. {
  366. _request.ContentLength = 0;
  367. }
  368. }
  369. }
  370. /// <summary>
  371. /// 设置代理
  372. /// </summary>
  373. /// <param name="item">参数对象</param>
  374. private void SetProxy(HttpItem item)
  375. {
  376. bool isIeProxy = false;
  377. if (!string.IsNullOrEmpty(item.ProxyIp))
  378. {
  379. isIeProxy = item.ProxyIp.ToLower().Contains("ieproxy");
  380. }
  381. if (!string.IsNullOrEmpty(item.ProxyIp) && !isIeProxy)
  382. {
  383. //设置代理服务器
  384. if (item.ProxyIp.Contains(":"))
  385. {
  386. string[] plist = item.ProxyIp.Split(':');
  387. WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()))
  388. {
  389. //建议连接
  390. Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd)
  391. };
  392. //给当前请求对象
  393. _request.Proxy = myProxy;
  394. }
  395. else
  396. {
  397. WebProxy myProxy = new WebProxy(item.ProxyIp, false)
  398. {
  399. //建议连接
  400. Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd)
  401. };
  402. //给当前请求对象
  403. _request.Proxy = myProxy;
  404. }
  405. }
  406. else if (isIeProxy)
  407. {
  408. //设置为IE代理
  409. }
  410. else
  411. {
  412. _request.Proxy = item.WebProxy;
  413. }
  414. }
  415. #endregion
  416. #region private main
  417. /// <summary>
  418. /// 回调验证证书问题
  419. /// </summary>
  420. /// <param name="sender">流对象</param>
  421. /// <param name="certificate">证书</param>
  422. /// <param name="chain">X509Chain</param>
  423. /// <param name="errors">SslPolicyErrors</param>
  424. /// <returns>bool</returns>
  425. private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
  426. /// <summary>
  427. /// 通过设置这个属性,可以在发出连接的时候绑定客户端发出连接所使用的IP地址。
  428. /// </summary>
  429. /// <param name="servicePoint"></param>
  430. /// <param name="remoteEndPoint"></param>
  431. /// <param name="retryCount"></param>
  432. /// <returns></returns>
  433. private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
  434. {
  435. return _ipEndPoint;//端口号
  436. }
  437. #endregion
  438. }
  439. /// <summary>
  440. /// Http请求参考类
  441. /// </summary>
  442. public class HttpItem
  443. {
  444. private string _url = string.Empty;
  445. /// <summary>
  446. /// 请求URL必须填写
  447. /// </summary>
  448. public string Url
  449. {
  450. get { return _url; }
  451. set { _url = value; }
  452. }
  453. private string _method = "GET";
  454. /// <summary>
  455. /// 请求方式默认为GET方式,当为POST方式时必须设置Postdata的值
  456. /// </summary>
  457. public string Method
  458. {
  459. get { return _method; }
  460. set { _method = value; }
  461. }
  462. private int _timeout = 90 * 1000;
  463. /// <summary>
  464. /// 默认请求超时时间,默认90秒
  465. /// </summary>
  466. public int Timeout
  467. {
  468. get { return _timeout; }
  469. set { _timeout = value; }
  470. }
  471. private int _readWriteTimeout = 60 * 1000;
  472. /// <summary>
  473. /// 默认写入Post数据超时间,默认60秒
  474. /// </summary>
  475. public int ReadWriteTimeout
  476. {
  477. get { return _readWriteTimeout; }
  478. set { _readWriteTimeout = value; }
  479. }
  480. private Boolean _keepAlive = true;
  481. /// <summary>
  482. /// 获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接默认为true。
  483. /// </summary>
  484. public Boolean KeepAlive
  485. {
  486. get { return _keepAlive; }
  487. set { _keepAlive = value; }
  488. }
  489. private string _accept = "text/html, application/xhtml+xml, */*";
  490. /// <summary>
  491. /// 请求标头值,默认为text/html, application/xhtml+xml, */*
  492. /// <para>1、application/json</para>
  493. /// </summary>
  494. public string Accept
  495. {
  496. get { return _accept; }
  497. set { _accept = value; }
  498. }
  499. private string _contentType = "text/html";
  500. /// <summary>
  501. /// 请求返回类型,默认为text/html
  502. /// <para>1、application/x-www-form-urlencoded;最常见的 POST 提交数据的方式</para>
  503. /// <para>2、multipart/form-data;主要用于上传文件</para>
  504. /// <para>3、application/json;服务端消息主体是序列化后的 JSON 字符串</para>
  505. /// <para>4、text/xml</para>
  506. /// </summary>
  507. public string ContentType
  508. {
  509. get { return _contentType; }
  510. set { _contentType = value; }
  511. }
  512. private string _userAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
  513. /// <summary>
  514. /// 客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
  515. /// 解读:MSIE 8.0代表IE8, Windows NT 6.1 对应操作系统 windows 7
  516. /// <para>1、IE各个版本典型的UserAgent如下:</para>
  517. /// <para>Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)</para>
  518. /// <para>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)</para>
  519. /// <para>Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)</para>
  520. /// <para>Mozilla/4.0 (compatible; MSIE 5.0; Windows NT)</para>
  521. /// <para>2、Firefox的UserAgent如下: </para>
  522. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1</para>
  523. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070309 Firefox/2.0.0.3</para>
  524. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12</para>
  525. /// <para>解读:N: 表示无安全加密 I: 表示弱安全加密 U: 表示强安全加密</para>
  526. /// <para>3、Opera典型的UserAgent如下:</para>
  527. /// <para>Opera/9.27 (Windows NT 5.2; U; zh-cn)</para>
  528. /// <para>Opera/8.0 (Macintosh; PPC Mac OS X; U; en)</para>
  529. /// <para>Mozilla/5.0 (Macintosh; PPC Mac OS X; U; en) Opera 8.0 </para>
  530. /// <para>4、Safari典型的UserAgent如下:</para>
  531. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Version/3.1 Safari/525.13</para>
  532. /// <para>Mozilla/5.0 (iPhone; U; CPU like Mac OS X) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A93 Safari/419.3</para>
  533. /// <para>5、Chrome的UserAgent如下:</para>
  534. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13 </para>
  535. /// <para>6、Navigator的UserAgent如下:</para>
  536. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080219 Firefox/2.0.0.12 Navigator/9.0.0.6</para>
  537. /// <para>7、安卓 原生浏览器</para>
  538. /// <para>Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; M032 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30</para>
  539. /// <para>8、iPhone Safria</para>
  540. /// <para>Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3</para>
  541. /// <para>9、塞班 自带浏览器</para>
  542. /// <para>Nokia5320/04.13 (SymbianOS/9.3; U; Series60/3.2 Mozilla/5.0; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413</para>
  543. /// </summary>
  544. public string UserAgent
  545. {
  546. get { return _userAgent; }
  547. set { _userAgent = value; }
  548. }
  549. private Encoding _encoding = null;
  550. /// <summary>
  551. /// 返回数据编码默认为NUll,可以自动识别,一般为utf-8,gbk,gb2312
  552. /// </summary>
  553. public Encoding Encoding
  554. {
  555. get { return _encoding; }
  556. set { _encoding = value; }
  557. }
  558. private PostDataType _postDataType = PostDataType.String;
  559. /// <summary>
  560. /// Post的数据类型
  561. /// </summary>
  562. public PostDataType PostDataType
  563. {
  564. get { return _postDataType; }
  565. set { _postDataType = value; }
  566. }
  567. private string _postdata = string.Empty;
  568. /// <summary>
  569. /// Post请求时要发送的字符串Post数据
  570. /// </summary>
  571. public string Postdata
  572. {
  573. get { return _postdata; }
  574. set { _postdata = value; }
  575. }
  576. private byte[] _postdataByte = null;
  577. /// <summary>
  578. /// Post请求时要发送的Byte类型的Post数据
  579. /// </summary>
  580. public byte[] PostdataByte
  581. {
  582. get { return _postdataByte; }
  583. set { _postdataByte = value; }
  584. }
  585. private WebProxy _webProxy;
  586. /// <summary>
  587. /// 设置代理对象,不想使用IE默认配置就设置为Null,而且不要设置ProxyIp
  588. /// </summary>
  589. public WebProxy WebProxy
  590. {
  591. get { return _webProxy; }
  592. set { _webProxy = value; }
  593. }
  594. private CookieCollection _cookiecollection = null;
  595. /// <summary>
  596. /// Cookie对象集合
  597. /// </summary>
  598. public CookieCollection CookieCollection
  599. {
  600. get { return _cookiecollection; }
  601. set { _cookiecollection = value; }
  602. }
  603. private string _cookie = string.Empty;
  604. /// <summary>
  605. /// 请求时的Cookie
  606. /// </summary>
  607. public string Cookie
  608. {
  609. get { return _cookie; }
  610. set { _cookie = value; }
  611. }
  612. private string _referer = string.Empty;
  613. /// <summary>
  614. /// 来源地址,上次访问地址
  615. /// </summary>
  616. public string Referer
  617. {
  618. get { return _referer; }
  619. set { _referer = value; }
  620. }
  621. private string _cerPath = string.Empty;
  622. /// <summary>
  623. /// 证书绝对路径
  624. /// </summary>
  625. public string CerPath
  626. {
  627. get { return _cerPath; }
  628. set { _cerPath = value; }
  629. }
  630. private Boolean _isToLower = false;
  631. /// <summary>
  632. /// 是否设置为全文小写,默认为不转化
  633. /// </summary>
  634. public Boolean IsToLower
  635. {
  636. get { return _isToLower; }
  637. set { _isToLower = value; }
  638. }
  639. private Boolean _allowautoredirect = false;
  640. /// <summary>
  641. /// 支持跳转页面,查询结果将是跳转后的页面,默认是不跳转
  642. /// </summary>
  643. public Boolean Allowautoredirect
  644. {
  645. get { return _allowautoredirect; }
  646. set { _allowautoredirect = value; }
  647. }
  648. private int _connectionlimit = 1024;
  649. /// <summary>
  650. /// 最大连接数
  651. /// </summary>
  652. public int Connectionlimit
  653. {
  654. get { return _connectionlimit; }
  655. set { _connectionlimit = value; }
  656. }
  657. private string _proxyusername = string.Empty;
  658. /// <summary>
  659. /// 代理Proxy 服务器用户名
  660. /// </summary>
  661. public string ProxyUserName
  662. {
  663. get { return _proxyusername; }
  664. set { _proxyusername = value; }
  665. }
  666. private string _proxypwd = string.Empty;
  667. /// <summary>
  668. /// 代理 服务器密码
  669. /// </summary>
  670. public string ProxyPwd
  671. {
  672. get { return _proxypwd; }
  673. set { _proxypwd = value; }
  674. }
  675. private string _proxyip = string.Empty;
  676. /// <summary>
  677. /// 代理 服务IP ,如果要使用IE代理就设置为ieproxy
  678. /// </summary>
  679. public string ProxyIp
  680. {
  681. get { return _proxyip; }
  682. set { _proxyip = value; }
  683. }
  684. private ResultType _resulttype = ResultType.String;
  685. /// <summary>
  686. /// 设置返回类型String和Byte
  687. /// </summary>
  688. public ResultType ResultType
  689. {
  690. get { return _resulttype; }
  691. set { _resulttype = value; }
  692. }
  693. private WebHeaderCollection _header = new WebHeaderCollection();
  694. /// <summary>
  695. /// header对象
  696. /// </summary>
  697. public WebHeaderCollection Header
  698. {
  699. get { return _header; }
  700. set { _header = value; }
  701. }
  702. private Version _protocolVersion = System.Net.HttpVersion.Version11;
  703. /// <summary>
  704. // 获取或设置用于请求的 HTTP 版本。返回结果:用于请求的 HTTP 版本。默认为 System.Net.HttpVersion.Version11。
  705. /// </summary>
  706. public Version ProtocolVersion
  707. {
  708. get { return _protocolVersion; }
  709. set { _protocolVersion = value; }
  710. }
  711. private Boolean _expect100Continue = false;
  712. /// <summary>
  713. /// 获取或设置一个 System.Boolean 值,该值确定是否使用 100-Continue 行为。如果 POST 请求需要 100-Continue 响应,则为 true;否则为 false。默认值为 true。
  714. /// </summary>
  715. public Boolean Expect100Continue
  716. {
  717. get { return _expect100Continue; }
  718. set { _expect100Continue = value; }
  719. }
  720. private X509CertificateCollection _clentCertificates;
  721. /// <summary>
  722. /// 设置509证书集合
  723. /// </summary>
  724. public X509CertificateCollection ClentCertificates
  725. {
  726. get { return _clentCertificates; }
  727. set { _clentCertificates = value; }
  728. }
  729. private Encoding _postEncoding = Encoding.Default;
  730. /// <summary>
  731. /// 设置或获取Post参数编码,默认的为Default编码
  732. /// </summary>
  733. public Encoding PostEncoding
  734. {
  735. get { return _postEncoding; }
  736. set { _postEncoding = value; }
  737. }
  738. private ResultCookieType _resultCookieType = ResultCookieType.String;
  739. /// <summary>
  740. /// Cookie返回类型,默认的是只返回字符串类型
  741. /// </summary>
  742. public ResultCookieType ResultCookieType
  743. {
  744. get { return _resultCookieType; }
  745. set { _resultCookieType = value; }
  746. }
  747. private ICredentials _iCredentials = CredentialCache.DefaultCredentials;
  748. /// <summary>
  749. /// 获取或设置请求的身份验证信息。
  750. /// </summary>
  751. public ICredentials ICredentials
  752. {
  753. get { return _iCredentials; }
  754. set { _iCredentials = value; }
  755. }
  756. /// <summary>
  757. /// 设置请求将跟随的重定向的最大数目
  758. /// </summary>
  759. private int _maximumAutomaticRedirections;
  760. public int MaximumAutomaticRedirections
  761. {
  762. get { return _maximumAutomaticRedirections; }
  763. set { _maximumAutomaticRedirections = value; }
  764. }
  765. private DateTime? _ifModifiedSince = null;
  766. /// <summary>
  767. /// 获取和设置IfModifiedSince,默认为当前日期和时间
  768. /// </summary>
  769. public DateTime? IfModifiedSince
  770. {
  771. get { return _ifModifiedSince; }
  772. set { _ifModifiedSince = value; }
  773. }
  774. #region ip-port
  775. private IPEndPoint _ipEndPoint = null;
  776. /// <summary>
  777. /// 设置本地的出口ip和端口
  778. /// </summary>]
  779. /// <example>
  780. ///item.IPEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"),80);
  781. /// </example>
  782. public IPEndPoint IPEndPoint
  783. {
  784. get { return _ipEndPoint; }
  785. set { _ipEndPoint = value; }
  786. }
  787. #endregion
  788. }
  789. /// <summary>
  790. /// Http返回参数类
  791. /// </summary>
  792. public class HttpResult
  793. {
  794. private string _cookie;
  795. /// <summary>
  796. /// Http请求返回的Cookie
  797. /// </summary>
  798. public string Cookie
  799. {
  800. get { return _cookie; }
  801. set { _cookie = value; }
  802. }
  803. private CookieCollection _cookieCollection;
  804. /// <summary>
  805. /// Cookie对象集合
  806. /// </summary>
  807. public CookieCollection CookieCollection
  808. {
  809. get { return _cookieCollection; }
  810. set { _cookieCollection = value; }
  811. }
  812. private string _html = string.Empty;
  813. /// <summary>
  814. /// 返回的String类型数据 只有ResultType.String时才返回数据,其它情况为空
  815. /// </summary>
  816. public string Html
  817. {
  818. get { return _html; }
  819. set { _html = value; }
  820. }
  821. private byte[] _resultByte;
  822. /// <summary>
  823. /// 返回的Byte数组 只有ResultType.Byte时才返回数据,其它情况为空
  824. /// </summary>
  825. public byte[] ResultByte
  826. {
  827. get { return _resultByte; }
  828. set { _resultByte = value; }
  829. }
  830. private WebHeaderCollection _header;
  831. /// <summary>
  832. /// header对象
  833. /// </summary>
  834. public WebHeaderCollection Header
  835. {
  836. get { return _header; }
  837. set { _header = value; }
  838. }
  839. private string _statusDescription;
  840. /// <summary>
  841. /// 返回状态说明
  842. /// </summary>
  843. public string StatusDescription
  844. {
  845. get { return _statusDescription; }
  846. set { _statusDescription = value; }
  847. }
  848. private HttpStatusCode _statusCode;
  849. /// <summary>
  850. /// 返回状态码,默认为OK
  851. /// </summary>
  852. public HttpStatusCode StatusCode
  853. {
  854. get { return _statusCode; }
  855. set { _statusCode = value; }
  856. }
  857. /// <summary>
  858. /// 最后访问的URl
  859. /// </summary>
  860. public string ResponseUri { get; set; }
  861. /// <summary>
  862. /// 获取重定向的URl
  863. /// </summary>
  864. public string RedirectUrl
  865. {
  866. get
  867. {
  868. try
  869. {
  870. if (Header != null && Header.Count > 0)
  871. {
  872. string baseurl = Header["location"].ToString().Trim();
  873. string locationurl = baseurl.ToLower();
  874. if (!string.IsNullOrWhiteSpace(locationurl))
  875. {
  876. bool b = locationurl.StartsWith("http://") || locationurl.StartsWith("https://");
  877. if (!b)
  878. {
  879. baseurl = new Uri(new Uri(ResponseUri), baseurl).AbsoluteUri;
  880. }
  881. }
  882. return baseurl;
  883. }
  884. }
  885. catch { }
  886. return string.Empty;
  887. }
  888. }
  889. }
  890. /// <summary>
  891. /// 返回类型
  892. /// </summary>
  893. public enum ResultType
  894. {
  895. /// <summary>
  896. /// 表示只返回字符串 只有Html有数据
  897. /// </summary>
  898. String,
  899. /// <summary>
  900. /// 表示返回字符串和字节流 ResultByte和Html都有数据返回
  901. /// </summary>
  902. Byte
  903. }
  904. /// <summary>
  905. /// Post的数据格式默认为string
  906. /// </summary>
  907. public enum PostDataType
  908. {
  909. /// <summary>
  910. /// 字符串类型,这时编码Encoding可不设置
  911. /// </summary>
  912. String,
  913. /// <summary>
  914. /// Byte类型,需要设置PostdataByte参数的值编码Encoding可设置为空
  915. /// </summary>
  916. Byte,
  917. /// <summary>
  918. /// 传文件,Postdata必须设置为文件的绝对路径,必须设置Encoding的值
  919. /// </summary>
  920. FilePath
  921. }
  922. /// <summary>
  923. /// Cookie返回类型
  924. /// </summary>
  925. public enum ResultCookieType
  926. {
  927. /// <summary>
  928. /// 只返回字符串类型的Cookie
  929. /// </summary>
  930. String,
  931. /// <summary>
  932. /// CookieCollection格式的Cookie集合同时也返回String类型的cookie
  933. /// </summary>
  934. CookieCollection
  935. }
  936. }