Could not establish trust relationship for the SSL/TLS secure channel 问题解决方法

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

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

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

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

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

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

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

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

return strResult;
}
return "";
}class

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

相关文章
相关标签/搜索