HttpIPHelper.cs 36 KB

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