解決HttpWebRequest訪問https請求被中止: 未能創建 SSL/TLS 安全通道


處理HttpWebRequest訪問https有安全證書的問題( 請求被中止: 未能創建 SSL/TLS 安全通道。)只需加上以下兩行代碼就行了。//處理HttpWebRequest訪問https有安全證書的問題( 請求被中止: 未能創建 SSL/TLS 安全通道。)ServicePointManager.ServerCertificateValidation…

處理HttpWebRequest訪問https有安全證書的問題( 請求被中止: 未能創建 SSL/TLS 安全通道。)

只需加上以下兩行代碼就行了。

 

//處理HttpWebRequest訪問https有安全證書的問題( 請求被中止: 未能創建 SSL/TLS 安全通道。)
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

以上代碼是.Net 4.5以上版本可以直接使用。

.Net 4.0版本使用下面代碼

ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

示例:

    /*發送微信訂閱通知消息*/
        private string sendWxNotify(string name,string tel,int goodsId, HttpContext context)
        {
            ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

            HttpWebRequest requet = (HttpWebRequest)WebRequest.Create("https://xx/postmessage?key=ad&name="+name+"&tel="+tel+"&id="+goodsId.ToString());
            requet.Method = "GET";
           
            using (HttpWebResponse response = (HttpWebResponse)requet.GetResponse()) 
            {
                StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.Default);
              return  sr.ReadToEnd();
            }
            return "";
        }

 

 

來源:http://geobook.net/news/show-1097.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM