使用HttpWebRequest请求https接口时抛出异常:请求被中止: 未能创建 SSL/TLS 安全通道。
代码如下:
public string PostDataToHttpsUrl(byte[] data, string url) { #region 创建httpWebRequest对象 HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest; httpRequest.ProtocolVersion = HttpVersion.Version10; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; if (httpRequest == null) { throw new ApplicationException( string.Format("Invalid url string: {0}", url) ); } #endregion #region 填充httpWebRequest的基本信息 httpRequest.UserAgent = sUserAgent; httpRequest.ContentType = sContentType; httpRequest.Method = "POST"; httpRequest.Proxy = null; #endregion #region 填充要post的内容 httpRequest.ContentLength = data.Length; Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Close(); #endregion #region 发送post请求到服务器并读取服务器返回信息 Stream responseStream; try { responseStream = httpRequest.GetResponse().GetResponseStream(); } catch (Exception e) { // log error //Console.WriteLine( // string.Format("POST操作发生异常:{0}", e.Message) // ); //Console.ReadLine(); throw e; } #endregion #region 读取服务器返回信息 string stringResponse = string.Empty; using (StreamReader responseReader = new StreamReader(responseStream, Encoding.GetEncoding(sResponseEncoding))) { stringResponse = responseReader.ReadToEnd(); } responseStream.Close(); return stringResponse; #endregion }
最佳解决方案
一、先修改请求代码尝试请求https接口,指定支持的tls协议版本如下:
#region 创建httpWebRequest对象 ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest; httpRequest.ProtocolVersion = HttpVersion.Version10; //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
二、如果代码层面不能解决问题,检查服务器是否支持当前接口指定的tls协议版本:
打开PowerShell,输入如下代码并运行:
[Net.ServicePointManager]::SecurityProtocol [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3 -bor [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
第一行代码检查支持TLS版本 第二行代码修改TLS支持
如果系统不支持tls版本,则根据系统版本升级相应补丁:https://support.microsoft.com/en-us/topic/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-winhttp-in-windows-c4bd73d2-31d7-761e-0178-11268bb10392
详细参考:https://www.xftsoft.com/news/jiaocheng/Could-not-create-SSL-TLS-secure-channel.html