HttpHelper.cs 33 KB

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