• [转]C#、VB.NET使用HttpWebRequest访问https地址(SSL)的实现


    用httpwebrequest访问一个SSL类型的地址 https://xxxx 时,报错 “未能为 SSL/TLS 安全通道建立信任关系(Could not establish trust relationship for the SSL/TLS secure channel)”

    查了下MSDN,找到了解决方法,SSL网站,连接时需要提供证书,对于非必须提供客户端证书的情况,只要返回一个安全确认即可。但是此方法的实现,在.NET 1.1 和 .NET 2.0 下是不同的,下面写出2个framework版本下的实现方法:

    使用的命名空间:

    using System.Net;
    using System.Net.Security;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;

    .Net 2.0

    public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        //直接确认,否则打不开
        return true;
    }
        
    private void button1_Click(object sender, EventArgs e)
    {
        ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
        HttpWebRequest req = (HttpWebRequest)WebRequest.CreateDefault(new Uri("https://zu14.cn/"));
        req.Method = "GET";
        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        //...正常使用了,和访问普通的 http:// 地址一样了
    

     .Net 1.1

    internal class AcceptAllCertificatePolicy : ICertificatePolicy
    {
        public AcceptAllCertificatePolicy()
        {
        }
    
        public bool CheckValidationResult(ServicePoint sPoint, System.Security.Cryptography.X509Certificates.X509Certificate cert, WebRequest wRequest, int certProb)
        {
            //直接确认
            return true;
        }
    }
        
    private void button1_Click(object sender, EventArgs e)
    {
        ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
        HttpWebRequest req = (HttpWebRequest)WebRequest.CreateDefault(new Uri("https://zu14.cn/"));
        req.Method = "GET";
        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        //...正常使用了,和访问普通的 http:// 地址一样了
    
  • 相关阅读:
    程序猿——踩bug之路
    原来python如此神奇
    结对编程——经验教训总结
    结对编程项目之队友个人项目优缺点
    结对编程:带ui设计的学生答题系统
    结对编程-自动出题项目代码分析
    记java的那些编辑器的故事之凌嘉文+李晓彤-结对编程
    结对编程-如何用精简的java代码写出这个系统
    数据库设计心得--知青村
    需求分析心得--住建执法项目小组知青村队
  • 原文地址:https://www.cnblogs.com/mimi001/p/1671489.html
Copyright © 2020-2023  润新知