当前位置: 代码迷 >> C# >> httpWebResponse get请求后的数据
  详细解决方案

httpWebResponse get请求后的数据

热度:151   发布时间:2016-05-05 03:00:03.0
【求助】httpWebResponse get请求后的数据
  // 发送请求  
        StringBuilder sbUrl = new StringBuilder(); // 请求URL内容  

        sbUrl.Append("http://wd.koudai.com/certDetails.html");
        sbUrl.Append("?");
        sbUrl.Append("userid=343280022");  
  
        String strUrl = sbUrl.ToString();  
        //解析xml文件  
        string resultXML = Demo.HttpWebResponseUtility.OpenReadWithHttps(Demo.HttpWebResponseUtility.CreateGetHttpResponse(sbUrl.ToString(), 200,"", null));  
  

using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Windows.Forms;
using System;
using System.Text;



/*    
 * 作者:申公
 * 日期:
 * 说明:此类提供http,POST和GET访问远程接口
 * */
namespace Demo
{
    /// <summary>
    /// 有关HTTP请求的辅助类 
    /// </summary>
    public class HttpWebResponseUtility
    {

        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";//浏览器
        private static Encoding requestEncoding = System.Text.Encoding.UTF8;//字符集

        /// <summary>  
        /// 创建GET方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.UserAgent = DefaultUserAgent;
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            return request.GetResponse() as HttpWebResponse;
        }


        /// <summary>  
        /// 创建POST方式的HTTP请求
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
        /// <returns></returns>
        public static HttpWebResponse CreatePostHttpResponse(string url, string parameters, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            HttpWebRequest request = null;
            Stream stream = null;//用于传参数的流

            try
            {
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    //创建证书文件
                    System.Security.Cryptography.X509Certificates.X509Certificate objx509 = new System.Security.Cryptography.X509Certificates.X509Certificate(Application.StartupPath + @"\\licensefile\zjs.cer");
                    //添加到请求里
                    request.ClientCertificates.Add(objx509);
                    request.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }

                request.Method = "POST";//传输方式
                request.ContentType = "application/x-www-form-urlencoded";//协议                
                request.UserAgent = DefaultUserAgent;//请求的客户端浏览器信息,默认IE                
                request.Timeout = 6000;//超时时间,写死6秒

                //随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }

                //如果需求POST传数据,转换成utf-8编码
                byte[] data = requestEncoding.GetBytes(parameters);
                request.ContentLength = data.Length;

                stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);

                stream.Close();
            }
            catch (Exception ee)
            {
                //写日志
                //LogHelper.
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }

            return request.GetResponse() as HttpWebResponse;
        }

        //验证服务器证书回调自动验证
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="HttpWebResponse">响应对象</param>
        /// <returns></returns>
        public static string OpenReadWithHttps(HttpWebResponse HttpWebResponse)
        {
            Stream responseStream = null;
            StreamReader sReader = null;
            String value = null;

            try
            {
                // 获取响应流
                responseStream = HttpWebResponse.GetResponseStream();
                // 对接响应流(以"utf-8"字符集)
                sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                // 开始读取数据
                value = sReader.ReadToEnd();
            }
            catch (Exception)
            {
                //日志异常
            }
            finally
            {
                //强制关闭
                if (sReader != null)
                {
                    sReader.Close();
                }
                if (responseStream != null)
                {
                    responseStream.Close();
                }
                if (HttpWebResponse != null)
                {
                    HttpWebResponse.Close();
                }
            }

            return value;
        }

        /// <summary>
        /// 入口方法:获取传回来的XML文件
        /// </summary>
        /// <param name="url">请求的URL</param>  
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
        /// <returns></returns>
        public static string GetResultXML(string url, string parameters, CookieCollection cookies)
        {
            return OpenReadWithHttps(CreatePostHttpResponse(url, parameters, cookies));
        }

    }
}

<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"><meta content="telephone=no" name="format-detection"><meta name="apple-touch-fullscreen" content="yes"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><title>微店</title><link href="http://s.koudai.com/css/common/base.css?v=2015082102" type="text/css" rel="stylesheet"><link href="http://s.koudai.com/css/index/index.css?v=2015082102" type="text/css" rel="stylesheet"></head><body><header id="common_hd" class="c_txt rel ellipsis_common_hd"><a id="hd_back" class="abs comm_p8 hide">返回</a> <a id="common_hd_logo" class="t_hide abs">微店</a><h1 class="hd_tle" id="index_back_tle">店铺详情</h1></header><div id="cert_main"><div id="index_loading" class="loading">&nbsp;</div></div><div id="tpl_content" class="hide"><header id="cert_header"><div id="cert_header_content"><a id="cert_logo"><img id="cert_logo_icon" src=""></a><div id="cert_shop_info"><ul id="cert_shop_info_ul"><li id="shopName">&nbsp;</li><li id="show_weixin_li" class="rel hide"></li><li id="openShopDate" class="hide">&nbsp;</li></ul></div><div id="shopAddr"><div class="shopAddr_logo"></div><div id="shopAddr_text"></div></div></div></header><ul id="cert_content"></ul></div><script src="http://s.koudai.com/script/common/base_H5.js?v=2015082102"></script><script>var Index={userid:function(){if(M.urlQuery("userid"))return parseInt(M.urlQuery("userid"));var e=location.hostname,i=e.split(".");return Number(i[0])}(),getShopInfo:function(){M.jsonp("http://wd.koudai.com/wd/shop/getPubInfo?param="+M.toJSON({userID:Index.userid}),function(e){console.log(e);var i=e.result,s=e.status,r=i.shop_grade;if(0===Number(s.status_code)&&i){$("#cert_logo_icon").attr("src",i.logo),$("#shopName").html(i.shopName),i.shop_addr?$("#shopAddr_text").html(i.shop_addr):$("#shopAddr").hide(),i.weixin&&$("#show_weixin_li").html("微信: "+i.weixin).show(),i.add_time&&$("#openShopDate").html("开店时间: "+i.add_time).show();var l="";if(Number(i.credit_type)){var t,a=i.credit_range;if(-1!=a.indexOf(",")){var n=a.split(",");t="("+n[0]+"-"+n[1]+"分)"}else t="("+a+"分以上)";l+='<li> <p> <br /><a href="http://weidian.com/vshop/1/help/help_detail.php?d=38" class="link" target="_blank"></script></body></html>

如上我请求回来的网页数据是这样的
我想得到$("#show_weixin_li").html("微信: "+i.weixin).show()的数据  就是 i.weixini 这个得到值之后 如下图 页面加载完后 是这样的

我想得到   18758919157  而不是$("#show_weixin_li").html("微信: "+i.weixin).show()这些
求大神告诉具体要怎么弄  最好贴点代码 本人小白
------解决思路----------------------
用字符串处理把"微信:"删掉不行么
------解决思路----------------------
正规则   \d+