Beispiel #1
0
        /// <summary>
        /// 根据相传入的数据,得到相应页面数据
        /// </summary>
        /// <param name="objhttpitem">参数类对象</param>
        /// <returns>返回HttpResult类型</returns>
        private HttpResult GetHttpRequestData(HttpItem objhttpitem)
        {
            //返回参数
            HttpResult result = new HttpResult();
            try
            {
                #region 得到请求的response

                using (response = (HttpWebResponse)request.GetResponse())
                {
                    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"];
                    MemoryStream _stream = new MemoryStream();
                    //GZIIP处理
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //开始读取流并设置编码方式
                        //new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
                        //.net4.0以下写法
                        _stream = GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
                    }
                    else
                    {
                        //开始读取流并设置编码方式
                        //response.GetResponseStream().CopyTo(_stream, 10240);
                        //.net4.0以下写法
                        _stream = GetMemoryStream(response.GetResponseStream());
                    }
                    //获取Byte
                    byte[] RawResponse = _stream.ToArray();
                    _stream.Close();
                    //是否返回Byte类型数据
                    if (objhttpitem.ResultType == ResultType.Byte)
                        result.ResultByte = RawResponse;
                    //从这里开始我们要无视编码了
                    if (encoding == null)
                    {
                        Match meta = Regex.Match(Encoding.Default.GetString(RawResponse), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
                        string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value.ToLower() : string.Empty;
                        charter = charter.Replace("\"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk");
                        if (charter.Length > 2)
                            encoding = Encoding.GetEncoding(charter.Trim());
                        else
                        {
                            if (string.IsNullOrEmpty(response.CharacterSet))
                                encoding = Encoding.UTF8;
                            else
                                encoding = Encoding.GetEncoding(response.CharacterSet);
                        }
                    }
                    //得到返回的HTML
                    result.Html = encoding.GetString(RawResponse);
                }

                #endregion 得到请求的response
            }
            catch (WebException ex)
            {
                //这里是在发生异常时返回的错误信息
                response = (HttpWebResponse)ex.Response;
                result.Html = ex.Message;
                if (response.StatusCode != null)
                {
                    result.StatusCode = response.StatusCode;
                    result.StatusDescription = response.StatusDescription;
                }
            }
            catch (Exception ex)
            {
                result.Html = ex.Message;
            }
            if (objhttpitem.IsToLower)
                result.Html = result.Html.ToLower();

            return result;
        }
Beispiel #2
0
 /// <summary>
 /// 为请求准备参数
 /// </summary>
 ///<param name="objhttpItem">参数列表</param>
 /// <param name="_Encoding">读取数据时的编码方式</param>
 private void SetRequest(HttpItem objhttpItem)
 {
     // 验证证书
     SetCer(objhttpItem);
     //设置Header参数
     if (objhttpItem.Header != null && objhttpItem.Header.Count > 0)
     {
         foreach (string item in objhttpItem.Header.AllKeys)
         {
             request.Headers.Add(item, objhttpItem.Header[item]);
         }
     }
     // 设置代理
     SetProxy(objhttpItem);
     //请求方式Get或者Post
     request.Method = objhttpItem.Method;
     request.Timeout = objhttpItem.Timeout;
     request.ReadWriteTimeout = objhttpItem.ReadWriteTimeout;
     //Accept
     request.Accept = objhttpItem.Accept;
     //ContentType返回类型
     request.ContentType = objhttpItem.ContentType;
     //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息
     request.UserAgent = objhttpItem.UserAgent;
     // 编码
     encoding = objhttpItem.Encoding;
     //设置Cookie
     SetCookie(objhttpItem);
     //来源地址
     request.Referer = objhttpItem.Referer;
     //是否执行跳转功能
     request.AllowAutoRedirect = objhttpItem.Allowautoredirect;
     //设置Post数据
     SetPostData(objhttpItem);
     //设置最大连接
     if (objhttpItem.Connectionlimit > 0)
         request.ServicePoint.ConnectionLimit = objhttpItem.Connectionlimit;
 }
Beispiel #3
0
 ///<summary>
 ///采用https协议访问网络,根据传入的URl地址,得到响应的数据字符串。
 ///</summary>
 ///<param name="objhttpItem">参数列表</param>
 ///<returns>String类型的数据</returns>
 public HttpResult GetHtml(HttpItem objhttpItem)
 {
     try
     {
         //准备参数
         SetRequest(objhttpItem);
     }
     catch (Exception ex)
     {
         HttpResult Result = new HttpResult()
         {
             Cookie = "",
             Header = null,
             Html = ex.Message,
             StatusDescription = "配置参考时报错"
         };
         return Result;
     }
     //调用专门读取数据的类
     return GetHttpRequestData(objhttpItem);
 }
Beispiel #4
0
 /// <summary>
 /// 设置代理
 /// </summary>
 /// <param name="objhttpItem">参数对象</param>
 private void SetProxy(HttpItem objhttpItem)
 {
     if (!string.IsNullOrEmpty(objhttpItem.ProxyIp))
     {
         //设置代理服务器
         if (objhttpItem.ProxyIp.Contains(":"))
         {
             string[] plist = objhttpItem.ProxyIp.Split(':');
             WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
             //建议连接
             myProxy.Credentials = new NetworkCredential(objhttpItem.ProxyUserName, objhttpItem.ProxyPwd);
             //给当前请求对象
             request.Proxy = myProxy;
         }
         else
         {
             WebProxy myProxy = new WebProxy(objhttpItem.ProxyIp, false);
             //建议连接
             myProxy.Credentials = new NetworkCredential(objhttpItem.ProxyUserName, objhttpItem.ProxyPwd);
             //给当前请求对象
             request.Proxy = myProxy;
         }
         //设置安全凭证
         request.Credentials = CredentialCache.DefaultNetworkCredentials;
     }
 }
Beispiel #5
0
 /// <summary>
 /// 设置Post数据
 /// </summary>
 /// <param name="objhttpItem">Http参数</param>
 private void SetPostData(HttpItem objhttpItem)
 {
     //验证在得到结果时是否有传入数据
     if (request.Method.Trim().ToLower().Contains("post"))
     {
         byte[] buffer = null;
         //写入Byte类型
         if (objhttpItem.PostDataType == PostDataType.Byte && objhttpItem.PostdataByte != null && objhttpItem.PostdataByte.Length > 0)
         {
             //验证在得到结果时是否有传入数据
             buffer = objhttpItem.PostdataByte;
         }//写入文件
         else if (objhttpItem.PostDataType == PostDataType.FilePath && !string.IsNullOrEmpty(objhttpItem.Postdata))
         {
             StreamReader r = new StreamReader(objhttpItem.Postdata, encoding);
             buffer = Encoding.Default.GetBytes(r.ReadToEnd());
             r.Close();
         } //写入字符串
         else if (!string.IsNullOrEmpty(objhttpItem.Postdata))
         {
             buffer = Encoding.Default.GetBytes(objhttpItem.Postdata);
         }
         if (buffer != null)
         {
             request.ContentLength = buffer.Length;
             request.GetRequestStream().Write(buffer, 0, buffer.Length);
         }
     }
 }
Beispiel #6
0
 /// <summary>
 /// 设置Cookie
 /// </summary>
 /// <param name="objhttpItem">Http参数</param>
 private void SetCookie(HttpItem objhttpItem)
 {
     if (!string.IsNullOrEmpty(objhttpItem.Cookie))
         //Cookie
         request.Headers[HttpRequestHeader.Cookie] = objhttpItem.Cookie;
     //设置Cookie
     if (objhttpItem.CookieCollection != null)
     {
         request.CookieContainer = new CookieContainer();
         request.CookieContainer.Add(objhttpItem.CookieCollection);
     }
 }
Beispiel #7
0
 /// <summary>
 /// 设置证书
 /// </summary>
 /// <param name="objhttpItem"></param>
 private void SetCer(HttpItem objhttpItem)
 {
     if (!string.IsNullOrEmpty(objhttpItem.CerPath))
     {
         //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
         ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
         //初始化对像,并设置请求的URL地址
         request = (HttpWebRequest)WebRequest.Create(objhttpItem.URL);
         //将证书添加到请求里
         request.ClientCertificates.Add(new X509Certificate(objhttpItem.CerPath));
     }
     else
         //初始化对像,并设置请求的URL地址
         request = (HttpWebRequest)WebRequest.Create(objhttpItem.URL);
 }
Beispiel #8
0
        /// <summary>
        /// 根据相传入的数据,得到相应页面数据
        /// </summary>
        /// <param name="objhttpitem">参数类对象</param>
        /// <returns>返回HttpResult类型</returns>
        private HttpResult GetHttpRequestData(HttpItem objhttpitem)
        {
            //返回参数
            HttpResult result = new HttpResult();

            try
            {
                #region 得到请求的response

                using (response = (HttpWebResponse)request.GetResponse())
                {
                    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"];
                    }
                    MemoryStream _stream = new MemoryStream();
                    //GZIIP处理
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //开始读取流并设置编码方式
                        //new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
                        //.net4.0以下写法
                        _stream = GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
                    }
                    else
                    {
                        //开始读取流并设置编码方式
                        //response.GetResponseStream().CopyTo(_stream, 10240);
                        //.net4.0以下写法
                        _stream = GetMemoryStream(response.GetResponseStream());
                    }
                    //获取Byte
                    byte[] RawResponse = _stream.ToArray();
                    _stream.Close();
                    //是否返回Byte类型数据
                    if (objhttpitem.ResultType == ResultType.Byte)
                    {
                        result.ResultByte = RawResponse;
                    }
                    //从这里开始我们要无视编码了
                    if (encoding == null)
                    {
                        Match  meta    = Regex.Match(Encoding.Default.GetString(RawResponse), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
                        string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value.ToLower() : string.Empty;
                        charter = charter.Replace("\"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk");
                        if (charter.Length > 2)
                        {
                            encoding = Encoding.GetEncoding(charter.Trim());
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(response.CharacterSet))
                            {
                                encoding = Encoding.UTF8;
                            }
                            else
                            {
                                encoding = Encoding.GetEncoding(response.CharacterSet);
                            }
                        }
                    }
                    //得到返回的HTML
                    result.Html = encoding.GetString(RawResponse);
                }

                #endregion 得到请求的response
            }
            catch (WebException ex)
            {
                //这里是在发生异常时返回的错误信息
                response    = (HttpWebResponse)ex.Response;
                result.Html = ex.Message;
                if (response.StatusCode != null)
                {
                    result.StatusCode        = response.StatusCode;
                    result.StatusDescription = response.StatusDescription;
                }
            }
            catch (Exception ex)
            {
                result.Html = ex.Message;
            }
            if (objhttpitem.IsToLower)
            {
                result.Html = result.Html.ToLower();
            }

            return(result);
        }