最近在寫一個跟第三方對接的數據同步服務,在本地都沒有問題,今天放到生產環境測試報錯:
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;
//}
//}