zoukankan      html  css  js  c++  java
  • Could not establish trust relationship for the SSL/TLS secure channel 问题解决方法

    最近在写一个跟第三方对接的数据同步服务,在本地都没有问题,今天放到生产环境测试报错:

    System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

    对方用的是https,看错误是证书问题,查了一些资料,貌似说这个问题的比较少,所以在此总结一下,以防以后用到。

    public string GetResponseData(string jsonData, string url)
    {
    byte[] bytes = Encoding.UTF8.GetBytes(jsonData);

    //1.1 在2.0下ServicePointManager.CertificatePolicy已经过时 
    //ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy(); 

    //2.0 https
    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentLength = bytes.Length;

    request.ContentType = "application/json";
    Stream reqstream = request.GetRequestStream();
    reqstream.Write(bytes, 0, bytes.Length);
    //设置连接超时时间
    request.Timeout = 60000;

    request.Headers.Set("Pragma", "no-cache");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
    Stream streamReceive = response.GetResponseStream();
    Encoding encoding = Encoding.UTF8;

    StreamReader streamReader = new StreamReader(streamReceive, encoding);
    string strResult = streamReader.ReadToEnd();
    streamReceive.Dispose();
    streamReader.Dispose();

    return strResult;
    }
    return "";
    }

    //2.0 https

    public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
    return true;
    }

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

  • 相关阅读:
    CF做题记录
    MobaXterm左侧没有文件列表,没有SCP,不显示文件夹问题处理
    使用FastJson转换Object时,空字符串丢失的解决办法【转】
    fastjson处理复杂对象,参数为null问题定位
    python 数据库连接池
    Git找回add 后,未commit的文件(使用reset -hard 命令导致文件清除)
    nginx过滤来自特定IP和user-agent的请求
    Redis实现排行榜(带二位小数点)
    系统不做任何优化,性能提升10%的方法
    二(二)、基于注解形式配置bean
  • 原文地址:https://www.cnblogs.com/iamsach/p/5912511.html
Copyright © 2011-2022 走看看