HttpHelper.cs 30 KB

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