错误异常>开发语言>C#
使用HttpWebRequest请求Https网站时,程序抛出错误:System.Net.WebException:“请求被中止: 未能创建 SSL/TLS 安全通道。”
具体代码如下:
if (en == null) en = Encoding.UTF8; String html; if (url.IndexOf("https") > -1) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls; } HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Timeout = 600000; //这里报错:System.Net.WebException:“请求被中止: 未能创建 SSL/TLS 安全通道。” WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream, en); String responseFromServer = reader.ReadToEnd(); html = responseFromServer; Encoding en2 = GetEncoding(response.ContentType);//responseFromServer reader.Close(); response.Close();
要保证HttpWebRequest请求HTTPS网站时,双方支持的SSL/TLS的版本一致才能建 SSL/TLS 安全通道。可以在创建HttpWebRequest之前把net支持的SSL/TLS协议全部指定上去,比如:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;