C#、VB.NET使用HttpWebRequest訪問https地址(SSL)的實現

來源:互聯網
上載者:User

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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.