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

本文介绍了解决使用HTTPWebRequest访问HTTPS网站时出现的信任关系错误的方法。提供了.NET1.1和.NET2.0两种环境下通过修改证书验证回调来绕过SSL证书验证的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

今天,有个网友问我:

用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:// 地址一样了

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值