12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136 |
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Diagnostics;
- using System.IO;
- using System.IO.Compression;
- using System.Net;
- using System.Net.Security;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- namespace SCC.Common
- {
-
-
-
- public class HttpIPHelper
- {
- #region 预定义方变量
-
- private Encoding _encoding = Encoding.Default;
-
- private Encoding _postencoding = Encoding.Default;
-
- private HttpWebRequest _request = null;
-
- private HttpWebResponse _response = null;
-
- private IPEndPoint _ipEndPoint = null;
-
- private string httpException = "";
- #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 = httpException;
- 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 = httpException;
- }
- }
- catch (Exception ex)
- {
- result.Html = httpException;
- }
- if (item.IsToLower)
- result.Html = result.Html.ToLower();
- return result;
- }
- #endregion Public
- #region GetData
-
-
-
-
-
- private void GetData(HttpItem item, HttpResult result)
- {
- #region base
-
- result.StatusCode = _response.StatusCode;
-
- result.StatusDescription = _response.StatusDescription;
-
- result.ResponseUri = _response.ResponseUri.ToString();
-
- 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 base
- #region byte
-
- byte[] responseByte = GetByte();
- #endregion byte
- #region Html
- if (responseByte != null && responseByte.Length > 0)
- {
-
- SetEncoding(item, result, responseByte);
-
- result.Html = Encoding.UTF8.GetString(responseByte);
- }
- else
- {
-
- result.Html = string.Empty;
- }
- #endregion Html
- }
-
-
-
-
-
-
- private void SetEncoding(HttpItem item, HttpResult result, byte[] responseByte)
- {
-
- if (item.ResultType == ResultType.Byte) result.ResultByte = responseByte;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
-
-
-
-
- private byte[] GetByte()
- {
- byte[] responseByte = null;
- MemoryStream stream;
-
- 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 GetData
- #region SetRequest
-
-
-
-
- private void SetRequest(HttpItem item)
- {
-
- SetCer(item);
- _request.Headers.Add(HttpRequestHeader.AcceptLanguage, item.AcceptLanguage);
- if (item.IPEndPoint != null)
- {
- _ipEndPoint = item.IPEndPoint;
-
- _request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
- }
-
- 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;
-
- string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
- if (item.FormData != null && item.FormData.Count > 0)
- _request.ContentType = "multipart/form-data; boundary=" + boundary;
- else
- _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;
- }
-
- if (item.FormData != null && item.FormData.Count > 0)
- SetFormData(item, boundary);
- else
- 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);
- }
- else
- {
- _request.ContentLength = 0;
- }
- }
- }
- private void SetFormData(HttpItem item, string boundary)
- {
-
- if (!_request.Method.Trim().ToLower().Contains("get"))
- {
- if (item.PostEncoding != null)
- {
- _postencoding = item.PostEncoding;
- }
- MemoryStream stream = new MemoryStream();
- string format = "--" + boundary + "\r\nContent-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}\r\n";
- foreach (string key in item.FormData.Keys)
- {
- string s = string.Format(format, key, item.FormData[key]);
- byte[] data = Encoding.UTF8.GetBytes(s);
- stream.Write(data, 0, data.Length);
- }
- byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
- stream.Write(foot_data, 0, foot_data.Length);
- _request.ContentLength = stream.Length;
- Stream requestStream = _request.GetRequestStream();
- stream.Position = 0L;
- stream.CopyTo(requestStream);
- stream.Close();
- }
- }
-
-
-
-
- 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()))
- {
-
- Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd)
- };
-
- _request.Proxy = myProxy;
- }
- else
- {
- WebProxy myProxy = new WebProxy(item.ProxyIp, false)
- {
-
- Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd)
- };
-
- _request.Proxy = myProxy;
- }
- }
- else if (isIeProxy)
- {
-
- }
- else
- {
- _request.Proxy = item.WebProxy;
- }
- }
- #endregion SetRequest
- #region private main
-
-
-
-
-
-
-
-
- private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
-
-
-
-
-
-
-
- private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
- {
- return _ipEndPoint;
- }
- #endregion private main
- }
-
-
-
- public class HttpItem
- {
- private string _url = string.Empty;
-
-
-
- public string Url
- {
- get { return _url; }
- set { _url = value; }
- }
- private string _method = "GET";
-
-
-
- public string Method
- {
- get { return _method; }
- set { _method = value; }
- }
- private int _timeout = 15 * 1000;
-
-
-
- public int Timeout
- {
- get { return _timeout; }
- set { _timeout = value; }
- }
- private int _readWriteTimeout = 30 * 1000;
-
-
-
- public int ReadWriteTimeout
- {
- get { return _readWriteTimeout; }
- set { _readWriteTimeout = value; }
- }
- private Boolean _keepAlive = true;
-
-
-
- public Boolean KeepAlive
- {
- get { return _keepAlive; }
- set { _keepAlive = value; }
- }
- private string _accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
-
-
-
-
- public string Accept
- {
- get { return _accept; }
- set { _accept = value; }
- }
- private string _contentType = "text/html";
-
-
-
-
-
-
-
- public string ContentType
- {
- get { return _contentType; }
- set { _contentType = value; }
- }
- private 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; }
- }
- private 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; }
- }
- private string _postdata = string.Empty;
-
-
-
- public string Postdata
- {
- get { return _postdata; }
- set { _postdata = value; }
- }
-
-
-
- public Dictionary<string, string> FormData { get; set; }
- 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; }
- }
- private CookieCollection _cookiecollection = null;
-
-
-
- public CookieCollection CookieCollection
- {
- get { return _cookiecollection; }
- set { _cookiecollection = value; }
- }
- private string _cookie = string.Empty;
-
-
-
- public string Cookie
- {
- get { return _cookie; }
- set { _cookie = value; }
- }
- private string _referer = string.Empty;
-
-
-
- public string Referer
- {
- get { return _referer; }
- set { _referer = value; }
- }
- private 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 bool _allowautoredirect = false;
-
-
-
- public bool 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 = System.Net.HttpVersion.Version11;
-
-
-
- public Version ProtocolVersion
- {
- get { return _protocolVersion; }
- set { _protocolVersion = value; }
- }
- private Boolean _expect100Continue = false;
-
-
-
- public Boolean Expect100Continue
- {
- get { return _expect100Continue; }
- set { _expect100Continue = value; }
- }
- private X509CertificateCollection _clentCertificates;
-
-
-
- public X509CertificateCollection ClentCertificates
- {
- get { return _clentCertificates; }
- set { _clentCertificates = value; }
- }
- private Encoding _postEncoding = Encoding.Default;
-
-
-
- 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; }
- }
- private string _acceptLanguage = "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2;q=0.9";
-
-
-
- public string AcceptLanguage
- {
- get { return _acceptLanguage; }
- set { _acceptLanguage = value; }
- }
- #region ip-port
- private IPEndPoint _ipEndPoint = null;
-
-
-
-
-
-
- public IPEndPoint IPEndPoint
- {
- get { return _ipEndPoint; }
- set { _ipEndPoint = value; }
- }
- #endregion ip-port
- }
-
-
-
- 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 string ResponseUri { get; set; }
-
-
-
- public string RedirectUrl
- {
- get
- {
- try
- {
- if (Header != null && Header.Count > 0)
- {
- string baseurl = Header["location"].ToString().Trim();
- string locationurl = baseurl.ToLower();
- if (!string.IsNullOrWhiteSpace(locationurl))
- {
- bool b = locationurl.StartsWith("http://") || locationurl.StartsWith("https://");
- if (!b)
- {
- baseurl = new Uri(new Uri(ResponseUri), baseurl).AbsoluteUri;
- }
- }
- return baseurl;
- }
- }
- catch { }
- return string.Empty;
- }
- }
- }
-
-
-
- public enum ResultType
- {
-
-
-
- String,
-
-
-
- Byte
- }
-
-
-
- public enum PostDataType
- {
-
-
-
- String,
-
-
-
- Byte,
-
-
-
- FilePath
- }
-
-
-
- public enum ResultCookieType
- {
-
-
-
- String,
-
-
-
- CookieCollection
- }
- }
|