HttpHelper.cs 33 KB

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