当前位置:   article > 正文

System.Net.WebException: 基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系。 ---> System.Security.Authentication.Authe...

c# http请求异常:system.net.webexception: 基础连接已经关闭

今天写程序的时候调用到一个第三方提供的https地址,访问此地址去获取加密的json格式数据,出现BUG

c#报错 :  System.Net.WebException: 基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系。 ---> System.Security.Authentication.AuthenticationException: 根据验证过程,远程证书无效。

 

引用:

private string callbackRefund(string url, string data)
{

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

  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);
    }
  }

 }

 解决方法:

步骤一:定义一个类,来对远程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上可用

转载于:https://www.cnblogs.com/bzsz-quan/p/9897979.html

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号