System.Net.WebException: 基礎鏈接已經關閉: 未能爲 SSL/TLS 安全通道創建信任關係。 ---> System.Security.Authentication.Authe

今天寫程序的時候調用到一個第三方提供的https地址,訪問此地址去獲取加密的json格式數據,出現BUGjson

c#報錯 :  System.Net.WebException: 基礎鏈接已經關閉: 未能爲 SSL/TLS 安全通道創建信任關係。 ---> System.Security.Authentication.AuthenticationException: 根據驗證過程,遠程證書無效。c#

 

引用:

private string callbackRefund(string url, string data)
{安全

       HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  request.Method = "POST";app

  byte[] bytes = UTF8Encoding.UTF8.GetBytes(data);
  request.ContentLength = bytes.Length;
  request.ContentType= "application/json";
  long x_ts = GetCurrentTimeUnix();
  request.Headers.Add("x-ts", x_ts.ToString());
  request.Headers.Add("x-hospitalId", "40617");
  request.Headers.Add("x-sig", "kinyer_debug_sign");
  using (Stream requestStream = request.GetRequestStream())
  {
    foreach (byte b in bytes)
    {
      requestStream.WriteByte(b);
    }
  }加密

  using (WebResponse response = request.GetResponse())
  {
    using (Stream responseStream = response.GetResponseStream())
    {
      byte[] responseContent;
      using (MemoryStream ms = new MemoryStream())
      {
        responseStream.CopyTo(ms);
        responseContent = ms.ToArray();
      }
    return UTF8Encoding.UTF8.GetString(responseContent);
    }
  }url

 }spa

 解決方法:debug

步驟一:定義一個類,來對遠程X.509證書的驗證,進行處理,返回爲true.咱們要本身定義一個類,而後在客戶單調用WCF服務以前,執行一次便可。代碼以下:部署

 

 public static class Util
    {
        /// <summary>
        /// Sets the cert policy.
        /// </summary>
        public static void SetCertificatePolicy()
        {
            ServicePointManager.ServerCertificateValidationCallback
                       += RemoteCertificateValidate;
        }

        /// <summary>
        /// Remotes the certificate validate.
        /// </summary>
        private static bool RemoteCertificateValidate(
           object sender, X509Certificate cert,
            X509Chain chain, SslPolicyErrors error)
        {
            // trust any certificate!!!
            System.Console.WriteLine("Warning, trust any certificate");
            return true;
        }
    }
 
步驟二:   你要在HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);調用操做點前先調用這個方法: Util.SetCertificatePolicy();

 

 

這樣實現了遠程訪問https地址   項目部署在win2012 2R上可用string

相關文章
相關標籤/搜索