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

  • 相关阅读:
    Windows 8.1 Visual Studio 2013 OpenGL 配置
    panic 和 recover的区别
    Beego操作数据库
    sql 中 inner join、left join 和 right join的区别
    Go实现网页爬虫
    SqlServer中 不区分大小写 和 全半角的写法
    循环语句
    switch语句
    iota枚举
    关于Go开发工具(LiteIDE)
  • 原文地址:https://www.cnblogs.com/iamsach/p/5912511.html
Copyright © 2020-2023  润新知