当前位置:首页 >.NET > 正文内容

HttpWebRequest验证证书文件获取网页内容

大滑稽11年前 (2014-03-24).NET1397

        /// 传入URL返回网页的html代码

        public string GetUrltoHtml(string Url)
        {
            StringBuilder content = new StringBuilder();
            try
            {
                // 与指定URL创建HTTP请求
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.KeepAlive = false;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8; .NET4.0C; .NET4.0E)";
                request.Method = "GET";
                request.Accept = "*/*";

                //创建证书文件
                X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer");

                //添加到请求里
                request.ClientCertificates.Add(objx509);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                // 获取对应HTTP请求的响应
                // 获取响应流
                Stream responseStream = response.GetResponseStream();
                // 对接响应流(以"GBK"字符集)
                StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("GBK"));
                // 开始读取数据
                Char[] sReaderBuffer = new Char[256];
                int count = sReader.Read(sReaderBuffer, 0, 256);
                while (count > 0)
                {
                    String tempStr = new String(sReaderBuffer, 0, count);
                    content.Append(tempStr);
                    count = sReader.Read(sReaderBuffer, 0, 256);
                }
                // 读取结束
                sReader.Close();
            }
            catch (Exception)
            {
                content = new StringBuilder("Runtime Error");
            }
            return content.ToString();
        }

 

 

//回调验证证书问题
        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受   
            return true;
        }

 

扫描二维码推送至手机访问。

版权声明:本文由第★一★次发布,如需转载请注明出处。

本文链接:http://www.wpers.net/post/59.html

“HttpWebRequest验证证书文件获取网页内容” 的相关文章

Cbo控件数据源绑定

 //Cbo控件数据源绑定DataTable DtType = noteType.GetTypeList("");         ...

C#遍历控件的方法

首先,要想遍历,就必须找到你想找的表单里面的所有控件,然后一个个的逐一比对,当找到了你需要的控件的时候,再做你需要的操作。1、foreach方法foreach (Control control in ...

Linq读写XML

         private List<News> GetNews(string html)    &n...

修改注册表限制软件使用次数

 private void Form1_Load(object sender, System.EventArgs e){RegistryKey RootKey,RegKey; //项名为:HKEY_CURRENT_USER\So...

c#中分页显示数据

     //c#中分页显示数据    public partial class Form1 : Form    {  ...

C#修改浏览器主页

string key = @"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main";      &n...