请求被中止: 未能创建 SSL/TLS 安全通道。原创
10人赞赏了该文章
7,348次浏览
编辑于2021年12月02日 16:09:23
问题描述: 今天用HttpWebRequest类Post请求https的接口,报错:请求被中止: 未能创建 SSL/TLS 安全通道。
解决方法: 参考如下函数,
在创建HttpWebRequest实例之前,加上 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
public static string PostData(byte[] data, string url, string contentType = "application/json", int timeout = 20) { //创建httpWebRequest对象 HttpWebRequest httpRequest = null; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; httpRequest = WebRequest.Create(url) as HttpWebRequest; httpRequest.ProtocolVersion = HttpVersion.Version10; } else { httpRequest = WebRequest.Create(url) as HttpWebRequest; } if (httpRequest == null) { throw new ApplicationException(string.Format("Invalid url string: {0}", url)); } //填充httpWebRequest的基本信息 httpRequest.ContentType = contentType; httpRequest.Method = "POST"; httpRequest.Timeout = timeout * 1000; //填充并发送要post的内容 httpRequest.ContentLength = data.Length; using (Stream requestStream = httpRequest.GetRequestStream()) { requestStream.Write(data, 0, data.Length); requestStream.Close(); } //发送post请求到服务器并读取服务器返回信息 var response = httpRequest.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { //读取服务器返回信息 string stringResponse = string.Empty; using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8)) { stringResponse = responseReader.ReadToEnd(); } responseStream.Close(); return stringResponse; } }
赞 10
10人点赞
还没有人点赞,快来当第一个点赞的人吧!
打赏
0人打赏
还没有人打赏,快来当第一个打赏的人吧!
推荐阅读