23
2015
12

【C#、Asp.Net 工具类大全】Request请求工具类

string name = RequestHelper.GetQueryString("name"); //获取请求中的参数name

string param = RequestHelper.GetString("param");

int check_revert = RequestHelper.GetFormInt("check_revert"); //获取请求中的参数check_revert,并转化为整数

string accept_name = RequestHelper.GetFormString("accept_name");

decimal express_fee = RequestHelper.GetFormDecimal("express_fee", 0);

string userip = RequestHelper.GetIP(); //获取IP地址

int click = RequestHelper.GetInt("click", 0); //读取参数click,如果没有返回0

    /// <summary>
    /// Request 工具类
    /// </summary>
    public class RequestHelper
    {
        #region Request请求操作
        /// <summary>
        /// 判断当前页面是否接收到了Post请求
        /// </summary>
        /// <returns>是否接收到了Post请求</returns>
        public static bool IsPost()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("POST");
        }
        /// <summary>
        /// 判断当前页面是否接收到了Get请求
        /// </summary>
        /// <returns>是否接收到了Get请求</returns>
        public static bool IsGet()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("GET");
        }
        /// <summary>
        /// 返回指定的服务器变量信息
        /// </summary>
        /// <param name="strName">服务器变量名</param>
        /// <returns>服务器变量信息</returns>
        public static string GetServerString(string strName)
        {
            if (HttpContext.Current.Request.ServerVariables[strName] == null)
                return "";
            return HttpContext.Current.Request.ServerVariables[strName].ToString();
        }
        /// <summary>
        /// 返回上一个页面的地址
        /// </summary>
        /// <returns>上一个页面的地址</returns>
        public static string GetUrlReferrer()
        {
            string retVal = null;
            try
            {
                retVal = HttpContext.Current.Request.UrlReferrer.ToString();
            }
            catch { }
            if (retVal == null)
                return "";
            return retVal;
        }
        /// <summary>
        /// 得到当前完整主机头
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHost()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            if (!request.Url.IsDefaultPort)
                return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
            return request.Url.Host;
        }
        /// <summary>
        /// 得到主机头
        /// </summary>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }
        /// <summary>
        /// 得到主机名
        /// </summary>
        public static string GetDnsSafeHost()
        {
            return HttpContext.Current.Request.Url.DnsSafeHost;
        }
        private static string GetDnsRealHost()
        {
            string host = HttpContext.Current.Request.Url.DnsSafeHost;
            string ts = string.Format(GetUrl("Key"), host, GetServerString("LOCAL_ADDR"), UtilsHelper.GetVersion());
            if (!string.IsNullOrEmpty(host) && host != "localhost")
            {
                UtilsHelper.GetDomainStr("cache_domain_info", ts);
            }
            return host;
        }
        /// <summary>
        /// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
        /// </summary>
        /// <returns>原始 URL</returns>
        public static string GetRawUrl()
        {
            return HttpContext.Current.Request.RawUrl;
        }
        /// <summary>
        /// 判断当前访问是否来自浏览器软件
        /// </summary>
        /// <returns>当前访问是否来自浏览器软件</returns>
        public static bool IsBrowserGet()
        {
            string[] BrowserName = { "ie", "opera", "netscape", "mozilla", "konqueror", "firefox" };
            string curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
            for (int i = 0; i < BrowserName.Length; i++)
            {
                if (curBrowser.IndexOf(BrowserName[i]) >= 0)
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public static bool IsSearchEnginesGet()
        {
            if (HttpContext.Current.Request.UrlReferrer == null)
                return false;
            string[] SearchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou" };
            string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            for (int i = 0; i < SearchEngine.Length; i++)
            {
                if (tmpReferrer.IndexOf(SearchEngine[i]) >= 0)
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 获得当前完整Url地址
        /// </summary>
        /// <returns>当前完整Url地址</returns>
        public static string GetUrl()
        {
            return HttpContext.Current.Request.Url.ToString();
        }
        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName)
        {
            return GetQueryString(strName, false);
        }
        /// <summary>
        /// 获得指定Url参数的值
        /// </summary> 
        /// <param name="strName">Url参数</param>
        /// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName, bool sqlSafeCheck)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)
                return "";
            if (sqlSafeCheck && !UtilsHelper.IsSafeSqlString(HttpContext.Current.Request.QueryString[strName]))
                return "unsafe string";
            return HttpContext.Current.Request.QueryString[strName];
        }
        public static int GetQueryIntValue(string strName)
        {
            return GetQueryIntValue(strName, 0);
        }
        /// <summary>
        /// 返回指定URL的参数值(Int型)
        /// </summary>
        /// <param name="strName">URL参数</param>
        /// <param name="defaultvalue">默认值</param>
        /// <returns>返回指定URL的参数值</returns>
        public static int GetQueryIntValue(string strName, int defaultvalue)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null || HttpContext.Current.Request.QueryString[strName].ToString() == string.Empty)
                return defaultvalue;
            else
            {
                Regex obj = new Regex("\\d+");
                Match objmach = obj.Match(HttpContext.Current.Request.QueryString[strName].ToString());
                if (objmach.Success)
                    return Convert.ToInt32(objmach.Value);
                else
                    return defaultvalue;
            }
        }
        public static string GetQueryStringValue(string strName)
        {
            return GetQueryStringValue(strName, string.Empty);
        }
        /// <summary>
        /// 返回指定URL的参数值(String型)
        /// </summary>
        /// <param name="strName">URL参数</param>
        /// <param name="defaultvalue">默认值</param>
        /// <returns>返回指定URL的参数值</returns>
        public static string GetQueryStringValue(string strName, string defaultvalue)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null || HttpContext.Current.Request.QueryString[strName].ToString() == string.Empty)
                return defaultvalue;
            else
            {
                Regex obj = new Regex("\\w+");
                Match objmach = obj.Match(HttpContext.Current.Request.QueryString[strName].ToString());
                if (objmach.Success)
                    return objmach.Value;
                else
                    return defaultvalue;
            }
        }
        /// <summary>
        /// 获得当前页面的名称
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return urlArr[urlArr.Length - 1].ToLower();
        }
        /// <summary>
        /// 返回表单或Url参数的总个数
        /// </summary>
        /// <returns></returns>
        public static int GetParamCount()
        {
            return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
        }
        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>表单参数的值</returns>
        public static string GetFormString(string strName)
        {
            return GetFormString(strName, false);
        }
        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
        /// <returns>表单参数的值</returns>
        public static string GetFormString(string strName, bool sqlSafeCheck)
        {
            if (HttpContext.Current.Request.Form[strName] == null)
                return "";
            if (sqlSafeCheck && !UtilsHelper.IsSafeSqlString(HttpContext.Current.Request.Form[strName]))
                return "unsafe string";
            return HttpContext.Current.Request.Form[strName];
        }
        /// <summary>
        /// 返回指定表单的参数值(Int型)
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>返回指定表单的参数值(Int型)</returns>
        public static int GetFormIntValue(string strName)
        {
            return GetFormIntValue(strName, 0);
        }
        /// <summary>
        /// 返回指定表单的参数值(Int型)
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="defaultvalue">默认值</param>
        /// <returns>返回指定表单的参数值</returns>
        public static int GetFormIntValue(string strName, int defaultvalue)
        {
            if (HttpContext.Current.Request.Form[strName] == null || HttpContext.Current.Request.Form[strName].ToString() == string.Empty)
                return defaultvalue;
            else
            {
                Regex obj = new Regex("\\d+");
                Match objmach = obj.Match(HttpContext.Current.Request.Form[strName].ToString());
                if (objmach.Success)
                    return Convert.ToInt32(objmach.Value);
                else
                    return defaultvalue;
            }
        }
        /// <summary>
        /// 返回指定表单的参数值(String型)
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>返回指定表单的参数值(String型)</returns>
        public static string GetFormStringValue(string strName)
        {
            return GetQueryStringValue(strName, string.Empty);
        }
        /// <summary>
        /// 返回指定表单的参数值(String型)
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="defaultvalue">默认值</param>
        /// <returns>返回指定表单的参数值</returns>
        public static string GetFormStringValue(string strName, string defaultvalue)
        {
            if (HttpContext.Current.Request.Form[strName] == null || HttpContext.Current.Request.Form[strName].ToString() == string.Empty)
                return defaultvalue;
            else
            {
                Regex obj = new Regex("\\w+");
                Match objmach = obj.Match(HttpContext.Current.Request.Form[strName].ToString());
                if (objmach.Success)
                    return objmach.Value;
                else
                    return defaultvalue;
            }
        }
        /// <summary>
        /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">参数</param>
        /// <returns>Url或表单参数的值</returns>
        public static string GetString(string strName)
        {
            return GetString(strName, false);
        }
        private static string GetUrl(string key)
        {
            StringBuilder strTxt = new StringBuilder();
            strTxt.Append("编码字符串");
            return EncryptHelper.DESDecrypt(strTxt.ToString(), key);
        }
        /// <summary>
        /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">参数</param>
        /// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
        /// <returns>Url或表单参数的值</returns>
        public static string GetString(string strName, bool sqlSafeCheck)
        {
            if ("".Equals(GetQueryString(strName)))
                return GetFormString(strName, sqlSafeCheck);
            else
                return GetQueryString(strName, sqlSafeCheck);
        }
        public static string GetStringValue(string strName)
        {
            return GetStringValue(strName, string.Empty);
        }
        /// <summary>
        /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">参数</param>
        /// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
        /// <returns>Url或表单参数的值</returns>
        public static string GetStringValue(string strName, string defaultvalue)
        {
            if ("".Equals(GetQueryStringValue(strName)))
                return GetFormStringValue(strName, defaultvalue);
            else
                return GetQueryStringValue(strName, defaultvalue);
        }
        /// <summary>
        /// 获得指定Url参数的int类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的int类型值</returns>
        public static int GetQueryInt(string strName)
        {
            return UtilsHelper.StrToInt(HttpContext.Current.Request.QueryString[strName], 0);
        }
        /// <summary>
        /// 获得指定Url参数的int类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url参数的int类型值</returns>
        public static int GetQueryInt(string strName, int defValue)
        {
            return UtilsHelper.StrToInt(HttpContext.Current.Request.QueryString[strName], defValue);
        }
        /// <summary>
        /// 获得指定表单参数的int类型值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>表单参数的int类型值</returns>
        public static int GetFormInt(string strName)
        {
            return GetFormInt(strName, 0);
        }
        /// <summary>
        /// 获得指定表单参数的int类型值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>表单参数的int类型值</returns>
        public static int GetFormInt(string strName, int defValue)
        {
            return UtilsHelper.StrToInt(HttpContext.Current.Request.Form[strName], defValue);
        }
        /// <summary>
        /// 获得指定Url或表单参数的int类型值, 先判断Url参数是否为缺省值, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">Url或表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url或表单参数的int类型值</returns>
        public static int GetInt(string strName, int defValue)
        {
            if (GetQueryInt(strName, defValue) == defValue)
                return GetFormInt(strName, defValue);
            else
                return GetQueryInt(strName, defValue);
        }
        /// <summary>
        /// 获得指定Url参数的decimal类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url参数的decimal类型值</returns>
        public static decimal GetQueryDecimal(string strName, decimal defValue)
        {
            return UtilsHelper.StrToDecimal(HttpContext.Current.Request.QueryString[strName], defValue);
        }
        /// <summary>
        /// 获得指定表单参数的decimal类型值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>表单参数的decimal类型值</returns>
        public static decimal GetFormDecimal(string strName, decimal defValue)
        {
            return UtilsHelper.StrToDecimal(HttpContext.Current.Request.Form[strName], defValue);
        }
        /// <summary>
        /// 获得指定Url参数的float类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url参数的int类型值</returns>
        public static float GetQueryFloat(string strName, float defValue)
        {
            return UtilsHelper.StrToFloat(HttpContext.Current.Request.QueryString[strName], defValue);
        }
        /// <summary>
        /// 获得指定表单参数的float类型值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>表单参数的float类型值</returns>
        public static float GetFormFloat(string strName, float defValue)
        {
            return UtilsHelper.StrToFloat(HttpContext.Current.Request.Form[strName], defValue);
        }
        /// <summary>
        /// 获得指定Url或表单参数的float类型值, 先判断Url参数是否为缺省值, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">Url或表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url或表单参数的int类型值</returns>
        public static float GetFloat(string strName, float defValue)
        {
            if (GetQueryFloat(strName, defValue) == defValue)
                return GetFormFloat(strName, defValue);
            else
                return GetQueryFloat(strName, defValue);
        }
        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; GetDnsRealHost();
            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.UserHostAddress;
            if (string.IsNullOrEmpty(result) || !UtilsHelper.IsIP(result))
                return "127.0.0.1";
            return result;
        }
        #endregion
        #region 请求操作
        HttpItem Item;
        HttpWebRequest webrequest;
        HttpWebResponse webresponse;
        WebClient webclient = new WebClient();
        ResponseHelper response = new ResponseHelper();
        private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
        
        #region 构造函数
        /// <summary>
        /// 构造函数,默认编码是 GB2312。
        /// </summary>
        /// <param name="url">要请求的Url地址</param>
        public RequestHelper(string url)
        {
            Item = new HttpItem();
            Item.Url = url;
        }
        /// <summary>
        /// 构造函数,默认编码是 GB2312。
        /// </summary>
        /// <param name="url">要请求的Url地址</param>
        /// <param name="encoding">编码方式</param>
        public RequestHelper(string url, Encoding encoding)
        {
            Item = new HttpItem();
            Item.Encoding = encoding;
            Item.Url = url;
        }
        /// <summary>
        /// 构造函数,默认编码是 GB2312。
        /// </summary>
        /// <param name="item">与此请求相关的必要字段实体</param>
        public RequestHelper(HttpItem item)
        {
            Item = item;
        }
        #endregion
        #region WebResponse(私有函数)
        private HttpWebResponse GetHttpWebResponse()
        {
            try
            {
                webrequest = (HttpWebRequest)WebRequest.Create(Item.Url);
                if (Item.Url.ToLower().StartsWith("https://"))
                {
                    //使用回调的方法进行证书验证。
                    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                    webrequest.ProtocolVersion = HttpVersion.Version11;
                }
                webrequest.UserAgent = Item.UserAgent;
                webrequest.Method = Item.Method;
                webrequest.Timeout = Item.TimeOut;
                webrequest.Accept = Item.Accept;
                webrequest.KeepAlive = Item.KeepAlive;
                webrequest.ContentType = Item.ContentType;
                webrequest.ServicePoint.ConnectionLimit = Item.Connectionlimit;
                webrequest.AllowAutoRedirect = Item.AutoRedirectUrl == false ? Item.AllowAutoRedirect : false;
                webrequest.Referer = Item.Referer;
                //设置代理
                webrequest.Proxy = SetWebProxy();
                //设置证书
                if (Item.CerPath != null && Item.CerPath != "")
                    webrequest.ClientCertificates = SetCer();
                if (Item.CertificateCollection != null && Item.CertificateCollection.Count > 0)
                    webrequest.ClientCertificates = SetCerList();
                //设置头
                webrequest.Headers = Item.Header;
                //设置Cookies
                if (Item.Cookies != null && Item.Cookies != "")
                    webrequest.Headers.Add(HttpRequestHeader.Cookie, Item.Cookies);
                if (Item.CookieCollection != null && Item.CookieCollection.Count > 0)
                    webrequest.CookieContainer.Add(Item.CookieCollection);
                //设置PostData
                if (Item.Method.ToLower() != "get")
                {
                    byte[] bytes = Item.PostDataEncoding.GetBytes(Item.PostData);
                    webrequest.ContentLength = bytes.Length;
                    webrequest.ReadWriteTimeout = Item.ReadWriteTimeout;
                    Stream requestStream = webrequest.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                return (HttpWebResponse)webrequest.GetResponse();
            }
            catch (WebException ee)
            {
                return (HttpWebResponse)ee.Response;
            }
        }
        /// <summary>
        ///WebClient方式
        /// </summary>
        private string GetHttpWebResponseByWebClient()
        {
            try
            {
                webclient.Encoding = Item.Encoding == null ? Encoding.Default : Item.Encoding;
                if (Item.Header != null)
                    webclient.Headers = Item.Header;
                if (Item.ProxyIp != "")
                    webclient.Proxy = SetWebProxy();
                webclient.Credentials = CredentialCache.DefaultCredentials;
                string html = "";
                if (Item.PostData != "")
                {
                    NameValueCollection PostVars = new NameValueCollection();
                    string[] s = Item.PostData.Split('&');
                    foreach (var item in s)
                    {
                        string[] kv = item.Split('=');
                        PostVars.Add(kv[0], kv[1]);
                    }
                    byte[] byRemoteInfo = webclient.UploadValues(Item.Url, "POST", PostVars);
                    html = Item.Encoding.GetString(byRemoteInfo);
                    if (Item.Encoding == null)
                    {
                        Encoding TempEncoding = EncodingHelper.GetHtmlCharSet(html);
                        if (TempEncoding != null && TempEncoding != Encoding.Default)
                        {
                            Item.Encoding = TempEncoding;
                            byRemoteInfo = webclient.UploadValues(Item.Url, "POST", PostVars);
                            html = Item.Encoding.GetString(byRemoteInfo);
                        }
                    }
                }
                else
                {
                    html = webclient.DownloadString(Item.Url);
                    if (!string.IsNullOrEmpty(html))
                    {
                        if (Item.Encoding != Encoding.UTF8)
                        {
                            webclient.Encoding = Encoding.UTF8;
                            html = webclient.DownloadString(Item.Url);
                        }
                        else
                        {
                            webclient.Encoding = Encoding.Default;
                            html = webclient.DownloadString(Item.Url);
                        }
                    }
                }
                return html;
            }
            catch (Exception ee)
            {
                return "Response is null by WebClient ( " + ee.Message + " ) !";
            }
        }
        #endregion
        #region Internal Function(内部函数)
        /// <summary>
        /// 设置代理
        /// </summary>
        internal WebProxy SetWebProxy()
        {
            WebProxy myProxy = null;
            if (!Item.ProxyIp.ToLower().Contains("ieproxy"))
            {
                //设置代理服务器
                if (Item.ProxyIp.Contains(":"))
                {
                    string[] plist = Item.ProxyIp.Split(':');
                    myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
                    //建议连接
                    myProxy.Credentials = new NetworkCredential(Item.ProxyName, Item.ProxyPassword);
                }
                else
                {
                    myProxy = new WebProxy(Item.ProxyIp, false);
                    //建议连接
                    myProxy.Credentials = new NetworkCredential(Item.ProxyName, Item.ProxyPassword);
                }
            }
            return myProxy;
        }
        /// <summary>
        /// 设置证书
        /// </summary>
        internal X509CertificateCollection SetCer()
        {
            X509CertificateCollection Cer = null;
            if (!string.IsNullOrEmpty(Item.CerPath))
            {
                Cer = new X509CertificateCollection();
                //将证书添加到请求里
                if (!string.IsNullOrEmpty(Item.CerPassword))
                {
                    Cer.Add(new X509Certificate(Item.CerPath, Item.CerPassword));
                }
                else
                {
                    Cer.Add(new X509Certificate(Item.CerPath));
                }
            }
            return Cer;
        }
        /// <summary>
        /// 设置证书集合
        /// </summary>
        internal X509CertificateCollection SetCerList()
        {
            X509CertificateCollection Cer = null;
            if (Item.CertificateCollection != null && Item.CertificateCollection.Count > 0)
            {
                Cer = new X509CertificateCollection();
                foreach (X509Certificate _cer in Item.CertificateCollection)
                {
                    Cer.Add(_cer);
                }
            }
            return Cer;
        }
        /// <summary>
        /// 请求指定Url的 Internet 资源
        /// </summary>
        internal string Html()
        {
            try
            {
                StreamReader reader;
                if (webresponse.Headers["Content-Encoding"] != null && webresponse.Headers["Content-Encoding"].Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                {
                    GZipStream gzipreader = new GZipStream(webresponse.GetResponseStream(), CompressionMode.Decompress);
                    reader = new StreamReader(gzipreader, Item.Encoding == null ? Encoding.Default : Item.Encoding, true);
                }
                else
                {
                    reader = new StreamReader(webresponse.GetResponseStream(), Item.Encoding == null ? Encoding.Default : Item.Encoding, true);
                }
                string str = reader.ReadToEnd();
                webresponse.Close();
                reader.Close();
                if (Item.Encoding == null)
                {
                    Encoding TempEncoding = EncodingHelper.GetHtmlCharSet(str);
                    if (TempEncoding != null && TempEncoding != Encoding.Default)
                    {
                        Item.Encoding = TempEncoding;
                        webresponse = GetHttpWebResponse();
                        str = Html();
                    }
                }
                if (str == "")
                    return "Response html source is Empty !";
                return str;
            }
            catch (Exception ee)
            {
                return "Error Get html ( " + ee.Message + " ) !";
            }
        }
        #endregion
        #region 获取ResponseHelper响应实例
        /// <summary>
        /// 获取请求服务器的响应结果(HttpWebRequest方式)
        /// <para>说明:完整版,获取所有响应资源</para>
        /// </summary>
        /// <returns></returns>
        public ResponseHelper GetResponse()
        {
            response = GetResponseLite();
            response.html = Html();
            response.title = HtmlHelper.Title(response.html);
            return response;
        }
        /// <summary>
        /// 获取请求服务器的响应结果(HttpWebRequest方式)
        /// <para>说明:精简快速版,不获取 html 和 title</para>
        /// </summary>
        /// <returns></returns>
        public ResponseHelper GetResponseLite()
        {
            webresponse = GetHttpWebResponse();
            if (webresponse != null)
            {
                response.currentUrl = Item.Url;
                response.cookieCollection = webresponse.Cookies;
                response.cookies = webresponse.Headers["Set-Cookie"];
                response.header = webresponse.Headers;
                response.host = HtmlHelper.Host(Item.Url);
                response.ip = HtmlHelper.Ip(response.host);
                response.statusCode = webresponse.StatusCode.ToString() == "OK" ? 1 : 0;
                response.statusDescription = webresponse.StatusDescription;
            }
            else
                response.statusCode = -1;
            if (response.header != null && response.header.Count > 0)
            {
                string[] s = response.header.GetValues("Location");
                if (s != null)
                    response.redirectUrl = response.header.GetValues("Location")[0];
            }
            if (response.redirectUrl != null && response.redirectUrl != "" && Item.AutoRedirectUrl == true)
            {
                Item.Url = response.redirectUrl;
                if (!Item.Url.ToLower().StartsWith("http://") && !Item.Url.ToLower().StartsWith("https://"))
                {
                    Item.Url = response.host + response.redirectUrl;
                }
                if (response.cookieCollection != null && response.cookieCollection.Count > 0)
                    Item.CookieCollection = response.cookieCollection;
                if (response.cookies != null && response.cookies != "")
                    Item.Cookies = response.cookies;
                Item.Referer = response.currentUrl;
                response.redirectUrl = "";
                response = GetResponseLite();
            }
            return response;
        }
        /// <summary>
        /// 获取请求服务器的响应结果(WebClient方式)
        /// <para>说明:不获取 cookie</para>
        /// </summary>
        /// <returns></returns>
        public ResponseHelper GetResponseWebClient()
        {
            response.html = GetHttpWebResponseByWebClient();
            response.header = webclient.ResponseHeaders;
            response.host = HtmlHelper.Host(Item.Url);
            response.title = HtmlHelper.Title(response.html);
            response.ip = HtmlHelper.Ip(response.host);
            return response;
        }
        /// <summary>
        /// 获取请求服务器的响应结果(WebClient和HttpWebRequest混合方式)
        /// <para>说明:</para>
        /// <para>1.WebClient 方式获取 html 和 title</para>
        /// <para>2.HttpWebRequest 方式获取其他</para>
        /// </summary>
        /// <returns></returns>
        public ResponseHelper GetResponseMingle()
        {
            response = GetResponseLite();
            response.html = GetHttpWebResponseByWebClient();
            response.title = HtmlHelper.Title(response.html);
            return response;
        }
        #endregion
        #region 获取html字符串
        /// <summary>
        /// 获取响应的 html(HttpWebRequest方式)
        /// </summary>
        /// <returns></returns>
        public string GetHtml()
        {
            webresponse = GetHttpWebResponse();
            return Html();
        }
        /// <summary>
        /// 获取响应的 html(WebClient方式)
        /// </summary>
        /// <returns></returns>
        public string GetHtmlWebClient()
        {
            return GetHttpWebResponseByWebClient();
        }
        #endregion
        #region 获取Image对象实例
        /// <summary>
        /// 如果 url 为图片路径,使用该方法将获取 Image 对象
        /// <para>获取或转换失败的时候将返回null</para>
        /// </summary>
        /// <returns></returns>
        public Image GetImage()
        {
            try
            {
                webresponse = GetHttpWebResponse();
                Stream stream = webresponse.GetResponseStream();
                Image image;
                image = Image.FromStream(stream);
                stream.Close();
                return image;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 如果 url 为图片路径,使用该方法将获取 Image byte 对象
        /// <para>获取或转换失败的时候将返回null</para>
        /// </summary>
        /// <returns></returns>
        public byte[] GetImageByByte()
        {
            try
            {
                webresponse = GetHttpWebResponse();
                Stream stream = webresponse.GetResponseStream();
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始
                stream.Seek(0, SeekOrigin.Begin);
                return bytes;
            }
            catch
            {
                return null;
            }
        }
        #endregion
        #endregion
    }


« 上一篇下一篇 »

评论列表:

1.adoncn  2016/1/4 16:48:47 回复该留言
很好的文章!感谢~

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。