[转]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:// 地址一样了

 

转载于:https://www.cnblogs.com/mimi001/archive/2010/02/22/1671489.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值