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