HttpWebRequest 请求https接口,一直提示未能创建 SSL/TLS 安全通道! 证书验证创建委托一直返回true 也不行。
因为是单向认证,所以这个肯定没啥问题,只能继续查资料了。
注意:如果是双向认证就需要加载证书才可以通信。
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
我用的是NET Farmwork 4,查了资料才知道根本不支持TLS,最高就到SSL3,所以我换到了NET Farmwork 4.5,完美解决。
完整代码:
private static readonly string DefaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36";
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static string HttpsPost(string url, string postData)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.GetEncoding("utf-8"); //选择编码字符集
byte[] data = encoding.GetBytes(postData); //转换为bytes数据
// 准备请求...
try
{
// 设置参数
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | (SecurityProtocolType)3072; //必须加上这一句,根据需要更改值
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Timeout = 30*1000; //30S
request.ContinueTimeout = 30 * 1000;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
request.UserAgent = DefaultUserAgent;
// request.TransferEncoding = encoding.HeaderName;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
string err = string.Empty;
return content;
}
catch (Exception ex)
{
string err = ex.Message;
return string.Empty;
}
}
亲测有效。