HttpHelper.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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 FCS.Common
  14. {
  15. /// <summary>
  16. /// Http连接操作帮助类
  17. /// </summary>
  18. public class HttpHelper
  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 = ConfigurationManager.AppSettings["HttpException"].ToString();
  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 = item.TranslationEncoding.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. /// <summary>
  496. /// 转译编码
  497. /// </summary>
  498. public Encoding TranslationEncoding { get; set; } = Encoding.UTF8;
  499. private string _method = "GET";
  500. /// <summary>
  501. /// 请求方式默认为GET方式,当为POST方式时必须设置Postdata的值
  502. /// </summary>
  503. public string Method
  504. {
  505. get { return _method; }
  506. set { _method = value; }
  507. }
  508. private int _timeout = 90 * 1000;
  509. /// <summary>
  510. /// 默认请求超时时间,默认90秒
  511. /// </summary>
  512. public int Timeout
  513. {
  514. get { return _timeout; }
  515. set { _timeout = value; }
  516. }
  517. private int _readWriteTimeout = 30 * 1000;
  518. /// <summary>
  519. /// 默认写入Post数据超时间,默认60秒
  520. /// </summary>
  521. public int ReadWriteTimeout
  522. {
  523. get { return _readWriteTimeout; }
  524. set { _readWriteTimeout = value; }
  525. }
  526. private Boolean _keepAlive = true;
  527. /// <summary>
  528. /// 获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接默认为true。
  529. /// </summary>
  530. public Boolean KeepAlive
  531. {
  532. get { return _keepAlive; }
  533. set { _keepAlive = value; }
  534. }
  535. private string _accept = "text/html, application/xhtml+xml, */*";
  536. /// <summary>
  537. /// 请求标头值,默认为text/html, application/xhtml+xml, */*
  538. /// <para>1、application/json</para>
  539. /// </summary>
  540. public string Accept
  541. {
  542. get { return _accept; }
  543. set { _accept = value; }
  544. }
  545. private string _contentType = "text/html";
  546. /// <summary>
  547. /// 请求返回类型,默认为text/html
  548. /// <para>1、application/x-www-form-urlencoded;最常见的 POST 提交数据的方式</para>
  549. /// <para>2、multipart/form-data;主要用于上传文件</para>
  550. /// <para>3、application/json;服务端消息主体是序列化后的 JSON 字符串</para>
  551. /// <para>4、text/xml</para>
  552. /// </summary>
  553. public string ContentType
  554. {
  555. get { return _contentType; }
  556. set { _contentType = value; }
  557. }
  558. private string _userAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
  559. /// <summary>
  560. /// 客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
  561. /// 解读:MSIE 8.0代表IE8, Windows NT 6.1 对应操作系统 windows 7
  562. /// <para>1、IE各个版本典型的UserAgent如下:</para>
  563. /// <para>Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)</para>
  564. /// <para>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)</para>
  565. /// <para>Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)</para>
  566. /// <para>Mozilla/4.0 (compatible; MSIE 5.0; Windows NT)</para>
  567. /// <para>2、Firefox的UserAgent如下: </para>
  568. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1</para>
  569. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070309 Firefox/2.0.0.3</para>
  570. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12</para>
  571. /// <para>解读:N: 表示无安全加密 I: 表示弱安全加密 U: 表示强安全加密</para>
  572. /// <para>3、Opera典型的UserAgent如下:</para>
  573. /// <para>Opera/9.27 (Windows NT 5.2; U; zh-cn)</para>
  574. /// <para>Opera/8.0 (Macintosh; PPC Mac OS X; U; en)</para>
  575. /// <para>Mozilla/5.0 (Macintosh; PPC Mac OS X; U; en) Opera 8.0 </para>
  576. /// <para>4、Safari典型的UserAgent如下:</para>
  577. /// <para>Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Version/3.1 Safari/525.13</para>
  578. /// <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>
  579. /// <para>5、Chrome的UserAgent如下:</para>
  580. /// <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>
  581. /// <para>6、Navigator的UserAgent如下:</para>
  582. /// <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>
  583. /// <para>7、安卓 原生浏览器</para>
  584. /// <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>
  585. /// <para>8、iPhone Safria</para>
  586. /// <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>
  587. /// <para>9、塞班 自带浏览器</para>
  588. /// <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>
  589. /// </summary>
  590. public string UserAgent
  591. {
  592. get { return _userAgent; }
  593. set { _userAgent = value; }
  594. }
  595. private Encoding _encoding = null;
  596. /// <summary>
  597. /// 返回数据编码默认为NUll,可以自动识别,一般为utf-8,gbk,gb2312
  598. /// </summary>
  599. public Encoding Encoding
  600. {
  601. get { return _encoding; }
  602. set { _encoding = value; }
  603. }
  604. private PostDataType _postDataType = PostDataType.String;
  605. /// <summary>
  606. /// Post的数据类型
  607. /// </summary>
  608. public PostDataType PostDataType
  609. {
  610. get { return _postDataType; }
  611. set { _postDataType = value; }
  612. }
  613. private string _postdata = string.Empty;
  614. /// <summary>
  615. /// Post请求时要发送的字符串Post数据
  616. /// </summary>
  617. public string Postdata
  618. {
  619. get { return _postdata; }
  620. set { _postdata = value; }
  621. }
  622. /// <summary>
  623. /// 表单提交数据
  624. /// </summary>
  625. public Dictionary<string, string> FormData { get; set; }
  626. private byte[] _postdataByte = null;
  627. /// <summary>
  628. /// Post请求时要发送的Byte类型的Post数据
  629. /// </summary>
  630. public byte[] PostdataByte
  631. {
  632. get { return _postdataByte; }
  633. set { _postdataByte = value; }
  634. }
  635. private WebProxy _webProxy;
  636. /// <summary>
  637. /// 设置代理对象,不想使用IE默认配置就设置为Null,而且不要设置ProxyIp
  638. /// </summary>
  639. public WebProxy WebProxy
  640. {
  641. get { return _webProxy; }
  642. set { _webProxy = value; }
  643. }
  644. private CookieCollection _cookiecollection = null;
  645. /// <summary>
  646. /// Cookie对象集合
  647. /// </summary>
  648. public CookieCollection CookieCollection
  649. {
  650. get { return _cookiecollection; }
  651. set { _cookiecollection = value; }
  652. }
  653. private string _cookie = string.Empty;
  654. /// <summary>
  655. /// 请求时的Cookie
  656. /// </summary>
  657. public string Cookie
  658. {
  659. get { return _cookie; }
  660. set { _cookie = value; }
  661. }
  662. private string _referer = string.Empty;
  663. /// <summary>
  664. /// 来源地址,上次访问地址
  665. /// </summary>
  666. public string Referer
  667. {
  668. get { return _referer; }
  669. set { _referer = value; }
  670. }
  671. private string _cerPath = string.Empty;
  672. /// <summary>
  673. /// 证书绝对路径
  674. /// </summary>
  675. public string CerPath
  676. {
  677. get { return _cerPath; }
  678. set { _cerPath = value; }
  679. }
  680. private Boolean _isToLower = false;
  681. /// <summary>
  682. /// 是否设置为全文小写,默认为不转化
  683. /// </summary>
  684. public Boolean IsToLower
  685. {
  686. get { return _isToLower; }
  687. set { _isToLower = value; }
  688. }
  689. private bool _allowautoredirect = false;
  690. /// <summary>
  691. /// 支持跳转页面,查询结果将是跳转后的页面,默认是不跳转
  692. /// </summary>
  693. public bool Allowautoredirect
  694. {
  695. get { return _allowautoredirect; }
  696. set { _allowautoredirect = value; }
  697. }
  698. private int _connectionlimit = 1024;
  699. /// <summary>
  700. /// 最大连接数
  701. /// </summary>
  702. public int Connectionlimit
  703. {
  704. get { return _connectionlimit; }
  705. set { _connectionlimit = value; }
  706. }
  707. private string _proxyusername = string.Empty;
  708. /// <summary>
  709. /// 代理Proxy 服务器用户名
  710. /// </summary>
  711. public string ProxyUserName
  712. {
  713. get { return _proxyusername; }
  714. set { _proxyusername = value; }
  715. }
  716. private string _proxypwd = string.Empty;
  717. /// <summary>
  718. /// 代理 服务器密码
  719. /// </summary>
  720. public string ProxyPwd
  721. {
  722. get { return _proxypwd; }
  723. set { _proxypwd = value; }
  724. }
  725. private string _proxyip = string.Empty;
  726. /// <summary>
  727. /// 代理 服务IP ,如果要使用IE代理就设置为ieproxy
  728. /// </summary>
  729. public string ProxyIp
  730. {
  731. get { return _proxyip; }
  732. set { _proxyip = value; }
  733. }
  734. private ResultType _resulttype = ResultType.String;
  735. /// <summary>
  736. /// 设置返回类型String和Byte
  737. /// </summary>
  738. public ResultType ResultType
  739. {
  740. get { return _resulttype; }
  741. set { _resulttype = value; }
  742. }
  743. private WebHeaderCollection _header = new WebHeaderCollection();
  744. /// <summary>
  745. /// header对象
  746. /// </summary>
  747. public WebHeaderCollection Header
  748. {
  749. get { return _header; }
  750. set { _header = value; }
  751. }
  752. private Version _protocolVersion = System.Net.HttpVersion.Version11;
  753. /// <summary>
  754. // 获取或设置用于请求的 HTTP 版本。返回结果:用于请求的 HTTP 版本。默认为 System.Net.HttpVersion.Version11。
  755. /// </summary>
  756. public Version ProtocolVersion
  757. {
  758. get { return _protocolVersion; }
  759. set { _protocolVersion = value; }
  760. }
  761. private Boolean _expect100Continue = false;
  762. /// <summary>
  763. /// 获取或设置一个 System.Boolean 值,该值确定是否使用 100-Continue 行为。如果 POST 请求需要 100-Continue 响应,则为 true;否则为 false。默认值为 true。
  764. /// </summary>
  765. public Boolean Expect100Continue
  766. {
  767. get { return _expect100Continue; }
  768. set { _expect100Continue = value; }
  769. }
  770. private X509CertificateCollection _clentCertificates;
  771. /// <summary>
  772. /// 设置509证书集合
  773. /// </summary>
  774. public X509CertificateCollection ClentCertificates
  775. {
  776. get { return _clentCertificates; }
  777. set { _clentCertificates = value; }
  778. }
  779. private Encoding _postEncoding = Encoding.Default;
  780. /// <summary>
  781. /// 设置或获取Post参数编码,默认的为Default编码
  782. /// </summary>
  783. public Encoding PostEncoding
  784. {
  785. get { return _postEncoding; }
  786. set { _postEncoding = value; }
  787. }
  788. private ResultCookieType _resultCookieType = ResultCookieType.String;
  789. /// <summary>
  790. /// Cookie返回类型,默认的是只返回字符串类型
  791. /// </summary>
  792. public ResultCookieType ResultCookieType
  793. {
  794. get { return _resultCookieType; }
  795. set { _resultCookieType = value; }
  796. }
  797. private ICredentials _iCredentials = CredentialCache.DefaultCredentials;
  798. /// <summary>
  799. /// 获取或设置请求的身份验证信息。
  800. /// </summary>
  801. public ICredentials ICredentials
  802. {
  803. get { return _iCredentials; }
  804. set { _iCredentials = value; }
  805. }
  806. /// <summary>
  807. /// 设置请求将跟随的重定向的最大数目
  808. /// </summary>
  809. private int _maximumAutomaticRedirections;
  810. public int MaximumAutomaticRedirections
  811. {
  812. get { return _maximumAutomaticRedirections; }
  813. set { _maximumAutomaticRedirections = value; }
  814. }
  815. private DateTime? _ifModifiedSince = null;
  816. /// <summary>
  817. /// 获取和设置IfModifiedSince,默认为当前日期和时间
  818. /// </summary>
  819. public DateTime? IfModifiedSince
  820. {
  821. get { return _ifModifiedSince; }
  822. set { _ifModifiedSince = value; }
  823. }
  824. 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";
  825. /// <summary>
  826. /// Accept-Language
  827. /// </summary>
  828. public string AcceptLanguage
  829. {
  830. get { return _acceptLanguage; }
  831. set { _acceptLanguage = value; }
  832. }
  833. #region ip-port
  834. private IPEndPoint _ipEndPoint = null;
  835. /// <summary>
  836. /// 设置本地的出口ip和端口
  837. /// </summary>]
  838. /// <example>
  839. ///item.IPEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"),80);
  840. /// </example>
  841. public IPEndPoint IPEndPoint
  842. {
  843. get { return _ipEndPoint; }
  844. set { _ipEndPoint = value; }
  845. }
  846. #endregion ip-port
  847. }
  848. /// <summary>
  849. /// Http返回参数类
  850. /// </summary>
  851. public class HttpResult
  852. {
  853. private string _cookie;
  854. /// <summary>
  855. /// Http请求返回的Cookie
  856. /// </summary>
  857. public string Cookie
  858. {
  859. get { return _cookie; }
  860. set { _cookie = value; }
  861. }
  862. private CookieCollection _cookieCollection;
  863. /// <summary>
  864. /// Cookie对象集合
  865. /// </summary>
  866. public CookieCollection CookieCollection
  867. {
  868. get { return _cookieCollection; }
  869. set { _cookieCollection = value; }
  870. }
  871. private string _html = string.Empty;
  872. /// <summary>
  873. /// 返回的String类型数据 只有ResultType.String时才返回数据,其它情况为空
  874. /// </summary>
  875. public string Html
  876. {
  877. get { return _html; }
  878. set { _html = value; }
  879. }
  880. private byte[] _resultByte;
  881. /// <summary>
  882. /// 返回的Byte数组 只有ResultType.Byte时才返回数据,其它情况为空
  883. /// </summary>
  884. public byte[] ResultByte
  885. {
  886. get { return _resultByte; }
  887. set { _resultByte = value; }
  888. }
  889. private WebHeaderCollection _header;
  890. /// <summary>
  891. /// header对象
  892. /// </summary>
  893. public WebHeaderCollection Header
  894. {
  895. get { return _header; }
  896. set { _header = value; }
  897. }
  898. private string _statusDescription;
  899. /// <summary>
  900. /// 返回状态说明
  901. /// </summary>
  902. public string StatusDescription
  903. {
  904. get { return _statusDescription; }
  905. set { _statusDescription = value; }
  906. }
  907. private HttpStatusCode _statusCode;
  908. /// <summary>
  909. /// 返回状态码,默认为OK
  910. /// </summary>
  911. public HttpStatusCode StatusCode
  912. {
  913. get { return _statusCode; }
  914. set { _statusCode = value; }
  915. }
  916. /// <summary>
  917. /// 最后访问的URl
  918. /// </summary>
  919. public string ResponseUri { get; set; }
  920. /// <summary>
  921. /// 获取重定向的URl
  922. /// </summary>
  923. public string RedirectUrl
  924. {
  925. get
  926. {
  927. try
  928. {
  929. if (Header != null && Header.Count > 0)
  930. {
  931. string baseurl = Header["location"].ToString().Trim();
  932. string locationurl = baseurl.ToLower();
  933. if (!string.IsNullOrWhiteSpace(locationurl))
  934. {
  935. bool b = locationurl.StartsWith("http://") || locationurl.StartsWith("https://");
  936. if (!b)
  937. {
  938. baseurl = new Uri(new Uri(ResponseUri), baseurl).AbsoluteUri;
  939. }
  940. }
  941. return baseurl;
  942. }
  943. }
  944. catch { }
  945. return string.Empty;
  946. }
  947. }
  948. }
  949. /// <summary>
  950. /// 返回类型
  951. /// </summary>
  952. public enum ResultType
  953. {
  954. /// <summary>
  955. /// 表示只返回字符串 只有Html有数据
  956. /// </summary>
  957. String,
  958. /// <summary>
  959. /// 表示返回字符串和字节流 ResultByte和Html都有数据返回
  960. /// </summary>
  961. Byte
  962. }
  963. /// <summary>
  964. /// Post的数据格式默认为string
  965. /// </summary>
  966. public enum PostDataType
  967. {
  968. /// <summary>
  969. /// 字符串类型,这时编码Encoding可不设置
  970. /// </summary>
  971. String,
  972. /// <summary>
  973. /// Byte类型,需要设置PostdataByte参数的值编码Encoding可设置为空
  974. /// </summary>
  975. Byte,
  976. /// <summary>
  977. /// 传文件,Postdata必须设置为文件的绝对路径,必须设置Encoding的值
  978. /// </summary>
  979. FilePath
  980. }
  981. /// <summary>
  982. /// Cookie返回类型
  983. /// </summary>
  984. public enum ResultCookieType
  985. {
  986. /// <summary>
  987. /// 只返回字符串类型的Cookie
  988. /// </summary>
  989. String,
  990. /// <summary>
  991. /// CookieCollection格式的Cookie集合同时也返回String类型的cookie
  992. /// </summary>
  993. CookieCollection
  994. }
  995. }