-
HttpHelper工具类
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net;
- using System.IO;
- using System.Text.RegularExpressions;
- using System.IO.Compression;
- using System.Security.Cryptography.X509Certificates;
- using System.Net.Security;
-
- namespace DotNet.Utilities
- {
-
-
-
- public class HttpHelper
- {
-
- #region 预定义方变量
-
- private Encoding encoding = Encoding.Default;
-
- private Encoding postencoding = Encoding.Default;
-
- private HttpWebRequest request = null;
-
- private HttpWebResponse response = null;
- #endregion
-
- #region Public
-
-
-
-
-
-
- public HttpResult GetHtml(HttpItem item)
- {
-
- HttpResult result = new HttpResult();
- try
- {
-
- SetRequest(item);
- }
- catch (Exception ex)
- {
- result.Cookie = string.Empty;
- result.Header = null;
- result.Html = ex.Message;
- result.StatusDescription = "配置参数时出错:" + ex.Message;
-
- return result;
- }
- try
- {
-
- using (response = (HttpWebResponse)request.GetResponse())
- {
- GetData(item, result);
- }
- }
- catch (WebException ex)
- {
- if (ex.Response != null)
- {
- using (response = (HttpWebResponse)ex.Response)
- {
- GetData(item, result);
- }
- }
- else
- {
- result.Html = ex.Message;
- }
- }
- catch (Exception ex)
- {
- result.Html = ex.Message;
- }
- if (item.IsToLower) result.Html = result.Html.ToLower();
- return result;
- }
- #endregion
-
- #region GetData
-
-
-
-
-
-
- private void GetData(HttpItem item, HttpResult result)
- {
- #region base
-
- result.StatusCode = response.StatusCode;
-
- result.StatusDescription = response.StatusDescription;
-
- result.Header = response.Headers;
-
- if (response.Cookies != null) result.CookieCollection = response.Cookies;
-
- if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
- #endregion
-
- #region byte
-
- byte[] ResponseByte = GetByte();
- #endregion
-
- #region Html
- if (ResponseByte != null & ResponseByte.Length > 0)
- {
-
- SetEncoding(item, result, ResponseByte);
-
- result.Html = encoding.GetString(ResponseByte);
- }
- else
- {
-
- result.Html = string.Empty;
- }
- #endregion
- }
-
-
-
-
-
-
- private void SetEncoding(HttpItem item, HttpResult result, byte[] ResponseByte)
- {
-
- if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte;
-
- if (encoding == null)
- {
- Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta[^<]*charset=([^<]*)["']", RegexOptions.IgnoreCase);
- string c = string.Empty;
- if (meta != null && meta.Groups.Count > 0)
- {
- c = meta.Groups[1].Value.ToLower().Trim();
- }
- if (c.Length > 2)
- {
- try
- {
- encoding = Encoding.GetEncoding(c.Replace(""", string.Empty).Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
- }
- catch
- {
- if (string.IsNullOrEmpty(response.CharacterSet))
- {
- encoding = Encoding.UTF8;
- }
- else
- {
- encoding = Encoding.GetEncoding(response.CharacterSet);
- }
- }
- }
- else
- {
- if (string.IsNullOrEmpty(response.CharacterSet))
- {
- encoding = Encoding.UTF8;
- }
- else
- {
- encoding = Encoding.GetEncoding(response.CharacterSet);
- }
- }
- }
- }
-
-
-
-
- private byte[] GetByte()
- {
- byte[] ResponseByte = null;
- MemoryStream _stream = new MemoryStream();
-
-
- if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
- {
-
- _stream = GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
- }
- else
- {
-
- _stream = GetMemoryStream(response.GetResponseStream());
- }
-
- ResponseByte = _stream.ToArray();
- _stream.Close();
- return ResponseByte;
- }
-
-
-
-
-
- private MemoryStream GetMemoryStream(Stream streamResponse)
- {
- MemoryStream _stream = new MemoryStream();
- int Length = 256;
- Byte[] buffer = new Byte[Length];
- int bytesRead = streamResponse.Read(buffer, 0, Length);
- while (bytesRead > 0)
- {
- _stream.Write(buffer, 0, bytesRead);
- bytesRead = streamResponse.Read(buffer, 0, Length);
- }
- return _stream;
- }
- #endregion
-
- #region SetRequest
-
-
-
-
-
- private void SetRequest(HttpItem item)
- {
-
- SetCer(item);
-
- if (item.Header != null && item.Header.Count > 0) foreach (string key in item.Header.AllKeys)
- {
- request.Headers.Add(key, item.Header[key]);
- }
-
- SetProxy(item);
- if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion;
- request.ServicePoint.Expect100Continue = item.Expect100Continue;
-
- request.Method = item.Method;
- request.Timeout = item.Timeout;
- request.KeepAlive = item.KeepAlive;
- request.ReadWriteTimeout = item.ReadWriteTimeout;
- if (item.IfModifiedSince != null) request.IfModifiedSince = Convert.ToDateTime(item.IfModifiedSince);
-
- request.Accept = item.Accept;
-
- request.ContentType = item.ContentType;
-
- request.UserAgent = item.UserAgent;
-
- encoding = item.Encoding;
-
- request.Credentials = item.ICredentials;
-
- SetCookie(item);
-
- request.Referer = item.Referer;
-
- request.AllowAutoRedirect = item.Allowautoredirect;
- if (item.MaximumAutomaticRedirections > 0)
- {
- request.MaximumAutomaticRedirections = item.MaximumAutomaticRedirections;
- }
-
- SetPostData(item);
-
- if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit;
- }
-
-
-
-
- private void SetCer(HttpItem item)
- {
- if (!string.IsNullOrEmpty(item.CerPath))
- {
-
- ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
-
- request = (HttpWebRequest)WebRequest.Create(item.URL);
- SetCerList(item);
-
- request.ClientCertificates.Add(new X509Certificate(item.CerPath));
- }
- else
- {
-
- request = (HttpWebRequest)WebRequest.Create(item.URL);
- SetCerList(item);
- }
- }
-
-
-
-
- private void SetCerList(HttpItem item)
- {
- if (item.ClentCertificates != null && item.ClentCertificates.Count > 0)
- {
- foreach (X509Certificate c in item.ClentCertificates)
- {
- request.ClientCertificates.Add(c);
- }
- }
- }
-
-
-
-
- private void SetCookie(HttpItem item)
- {
- if (!string.IsNullOrEmpty(item.Cookie)) request.Headers[HttpRequestHeader.Cookie] = item.Cookie;
-
- if (item.ResultCookieType == ResultCookieType.CookieCollection)
- {
- request.CookieContainer = new CookieContainer();
- if (item.CookieCollection != null && item.CookieCollection.Count > 0)
- request.CookieContainer.Add(item.CookieCollection);
- }
- }
-
-
-
-
- private void SetPostData(HttpItem item)
- {
-
- if (!request.Method.Trim().ToLower().Contains("get"))
- {
- if (item.PostEncoding != null)
- {
- postencoding = item.PostEncoding;
- }
- byte[] buffer = null;
-
- if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
- {
-
- buffer = item.PostdataByte;
- }
- else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrEmpty(item.Postdata))
- {
- StreamReader r = new StreamReader(item.Postdata, postencoding);
- buffer = postencoding.GetBytes(r.ReadToEnd());
- r.Close();
- }
- else if (!string.IsNullOrEmpty(item.Postdata))
- {
- buffer = postencoding.GetBytes(item.Postdata);
- }
- if (buffer != null)
- {
- request.ContentLength = buffer.Length;
- request.GetRequestStream().Write(buffer, 0, buffer.Length);
- }
- }
- }
-
-
-
-
- private void SetProxy(HttpItem item)
- {
- bool isIeProxy = false;
- if (!string.IsNullOrEmpty(item.ProxyIp))
- {
- isIeProxy = item.ProxyIp.ToLower().Contains("ieproxy");
- }
- if (!string.IsNullOrEmpty(item.ProxyIp) && !isIeProxy)
- {
-
- if (item.ProxyIp.Contains(":"))
- {
- string[] plist = item.ProxyIp.Split(':');
- WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
-
- myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
-
- request.Proxy = myProxy;
- }
- else
- {
- WebProxy myProxy = new WebProxy(item.ProxyIp, false);
-
- myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
-
- request.Proxy = myProxy;
- }
- }
- else if (isIeProxy)
- {
-
- }
- else
- {
- request.Proxy = item.WebProxy;
- }
- }
- #endregion
-
- #region private main
-
-
-
-
-
-
-
-
- private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
- #endregion
- }
-
-
-
- public class HttpItem
- {
- string _URL = string.Empty;
-
-
-
- public string URL
- {
- get { return _URL; }
- set { _URL = value; }
- }
- string _Method = "GET";
-
-
-
- public string Method
- {
- get { return _Method; }
- set { _Method = value; }
- }
- int _Timeout = 100000;
-
-
-
- public int Timeout
- {
- get { return _Timeout; }
- set { _Timeout = value; }
- }
- int _ReadWriteTimeout = 30000;
-
-
-
- public int ReadWriteTimeout
- {
- get { return _ReadWriteTimeout; }
- set { _ReadWriteTimeout = value; }
- }
- Boolean _KeepAlive = true;
-
-
-
- public Boolean KeepAlive
- {
- get { return _KeepAlive; }
- set { _KeepAlive = value; }
- }
- string _Accept = "text/html, application/xhtml+xml, */*";
-
-
-
- public string Accept
- {
- get { return _Accept; }
- set { _Accept = value; }
- }
- string _ContentType = "text/html";
-
-
-
- public string ContentType
- {
- get { return _ContentType; }
- set { _ContentType = value; }
- }
- string _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
-
-
-
- public string UserAgent
- {
- get { return _UserAgent; }
- set { _UserAgent = value; }
- }
- Encoding _Encoding = null;
-
-
-
- public Encoding Encoding
- {
- get { return _Encoding; }
- set { _Encoding = value; }
- }
- private PostDataType _PostDataType = PostDataType.String;
-
-
-
- public PostDataType PostDataType
- {
- get { return _PostDataType; }
- set { _PostDataType = value; }
- }
- string _Postdata = string.Empty;
-
-
-
- public string Postdata
- {
- get { return _Postdata; }
- set { _Postdata = value; }
- }
- private byte[] _PostdataByte = null;
-
-
-
- public byte[] PostdataByte
- {
- get { return _PostdataByte; }
- set { _PostdataByte = value; }
- }
- private WebProxy _WebProxy;
-
-
-
- public WebProxy WebProxy
- {
- get { return _WebProxy; }
- set { _WebProxy = value; }
- }
-
- CookieCollection cookiecollection = null;
-
-
-
- public CookieCollection CookieCollection
- {
- get { return cookiecollection; }
- set { cookiecollection = value; }
- }
- string _Cookie = string.Empty;
-
-
-
- public string Cookie
- {
- get { return _Cookie; }
- set { _Cookie = value; }
- }
- string _Referer = string.Empty;
-
-
-
- public string Referer
- {
- get { return _Referer; }
- set { _Referer = value; }
- }
- string _CerPath = string.Empty;
-
-
-
- public string CerPath
- {
- get { return _CerPath; }
- set { _CerPath = value; }
- }
- private Boolean isToLower = false;
-
-
-
- public Boolean IsToLower
- {
- get { return isToLower; }
- set { isToLower = value; }
- }
- private Boolean allowautoredirect = false;
-
-
-
- public Boolean Allowautoredirect
- {
- get { return allowautoredirect; }
- set { allowautoredirect = value; }
- }
- private int connectionlimit = 1024;
-
-
-
- public int Connectionlimit
- {
- get { return connectionlimit; }
- set { connectionlimit = value; }
- }
- private string proxyusername = string.Empty;
-
-
-
- public string ProxyUserName
- {
- get { return proxyusername; }
- set { proxyusername = value; }
- }
- private string proxypwd = string.Empty;
-
-
-
- public string ProxyPwd
- {
- get { return proxypwd; }
- set { proxypwd = value; }
- }
- private string proxyip = string.Empty;
-
-
-
- public string ProxyIp
- {
- get { return proxyip; }
- set { proxyip = value; }
- }
- private ResultType resulttype = ResultType.String;
-
-
-
- public ResultType ResultType
- {
- get { return resulttype; }
- set { resulttype = value; }
- }
- private WebHeaderCollection header = new WebHeaderCollection();
-
-
-
- public WebHeaderCollection Header
- {
- get { return header; }
- set { header = value; }
- }
-
- private Version _ProtocolVersion;
-
-
-
-
- public Version ProtocolVersion
- {
- get { return _ProtocolVersion; }
- set { _ProtocolVersion = value; }
- }
- private Boolean _expect100continue = true;
-
-
-
- public Boolean Expect100Continue
- {
- get { return _expect100continue; }
- set { _expect100continue = value; }
- }
- private X509CertificateCollection _ClentCertificates;
-
-
-
- public X509CertificateCollection ClentCertificates
- {
- get { return _ClentCertificates; }
- set { _ClentCertificates = value; }
- }
- private Encoding _PostEncoding;
-
-
-
- public Encoding PostEncoding
- {
- get { return _PostEncoding; }
- set { _PostEncoding = value; }
- }
- private ResultCookieType _ResultCookieType = ResultCookieType.String;
-
-
-
- public ResultCookieType ResultCookieType
- {
- get { return _ResultCookieType; }
- set { _ResultCookieType = value; }
- }
-
- private ICredentials _ICredentials = CredentialCache.DefaultCredentials;
-
-
-
- public ICredentials ICredentials
- {
- get { return _ICredentials; }
- set { _ICredentials = value; }
- }
-
-
-
- private int _MaximumAutomaticRedirections;
-
- public int MaximumAutomaticRedirections
- {
- get { return _MaximumAutomaticRedirections; }
- set { _MaximumAutomaticRedirections = value; }
- }
-
- private DateTime? _IfModifiedSince = null;
-
-
-
- public DateTime? IfModifiedSince
- {
- get { return _IfModifiedSince; }
- set { _IfModifiedSince = value; }
- }
-
- }
-
-
-
- public class HttpResult
- {
- private string _Cookie;
-
-
-
- public string Cookie
- {
- get { return _Cookie; }
- set { _Cookie = value; }
- }
-
- private CookieCollection _CookieCollection;
-
-
-
- public CookieCollection CookieCollection
- {
- get { return _CookieCollection; }
- set { _CookieCollection = value; }
- }
- private string _html = string.Empty;
-
-
-
- public string Html
- {
- get { return _html; }
- set { _html = value; }
- }
- private byte[] _ResultByte;
-
-
-
- public byte[] ResultByte
- {
- get { return _ResultByte; }
- set { _ResultByte = value; }
- }
- private WebHeaderCollection _Header;
-
-
-
- public WebHeaderCollection Header
- {
- get { return _Header; }
- set { _Header = value; }
- }
- private string _StatusDescription;
-
-
-
- public string StatusDescription
- {
- get { return _StatusDescription; }
- set { _StatusDescription = value; }
- }
- private HttpStatusCode _StatusCode;
-
-
-
- public HttpStatusCode StatusCode
- {
- get { return _StatusCode; }
- set { _StatusCode = value; }
- }
- }
-
-
-
- public enum ResultType
- {
-
-
-
- String,
-
-
-
- Byte
- }
-
-
-
- public enum PostDataType
- {
-
-
-
- String,
-
-
-
- Byte,
-
-
-
- FilePath
- }
-
-
-
- public enum ResultCookieType
- {
-
-
-
- String,
-
-
-
- CookieCollection
- }
- }
-
相关阅读:
PAT 甲级 1057 Stack(树状数组解法)
LeetCode 815 公交路线
201771010123汪慧和《面向对象程序设计JAVA》第六周实验总结
汪慧和201771010123《面向对象程序设计JAVA》第四周实验总结
汪慧和201771010123《面向对象程序设计(Java)》第三周学习总结
201771010123汪慧和《面向对象程序设计Java》第二周学习总结
汪慧和201771010123
201771010119穷吉1
学习进度条201771010119穷吉
穷吉201771010119*
-
原文地址:https://www.cnblogs.com/dangzhenjiuhao/p/5622038.html
Copyright © 2020-2023
润新知