HttpHelper.cs 29 KB

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