Requesting html over https with c# Webclient
我正在从无法控制的站点通过c#WebClient类尝试各种html资源。
当我尝试访问网址时,例如
" https://archive.org/details/OTRR_In_The_Name_Of_The_Law_Singles"
我得到错误:
System.Net.WebException:请求已中止:无法创建SSL / TLS安全通道。
我发现了一些解决方案,建议我使用以下代码来忽略证书要求,并使Web客户端充当浏览器,但是我仍然收到相同的错误
1 2 3 4 5 6 7 8 9 10 11 12 13 | ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback( delegate { return true; }); using(WebClient webClient = new WebClient()) { webClient.Headers["User-Agent"] ="Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)"; webClient.Headers["Accept"] ="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; webClient.Headers["Accept-Language"] ="en-us,en;q=0.5"; webClient.Headers["Accept-Encoding"] ="gzip,deflate"; webClient.Headers["Accept-Charset"] ="ISO-8859-1,utf-8;q=0.7,*;q=0.7"; StreamReader sr = new StreamReader(webClient.OpenRead(inputString)); } |
阅读以下内容:http://support.microsoft.com/kb/915599
您正在访问的服务器不支持TLS,因此您需要强制其使用SSL3。
将以下行添加到您的呼叫中:
1 | ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; |
这是一个完整的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | using System; using System.IO; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; class Program { static void Main(string[] args) { Uri address = new Uri("https://archive.org/details/OTRR_In_The_Name_Of_The_Law_Singles"); ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 ; using (WebClient webClient = new WebClient()) { var stream = webClient.OpenRead(address); using (StreamReader sr =new StreamReader(stream)) { var page = sr.ReadToEnd(); } } } /// <summary> /// Certificate validation callback. /// </summary> private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { // If the certificate is a valid, signed certificate, return true. if (error == System.Net.Security.SslPolicyErrors.None) { return true; } Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'", cert.Subject, error.ToString()); return false; } |
在.net Framework 4.0中添加
1 | ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2 |
只需在
1 | System.Net.ServicePointManager.ServerCertificateValidationCallback += (send, certificate, chain, sslPolicyErrors) => { return true; }; |
那应该解决SSL / TLS错误
我尝试了这个示例并收到了错误
"请求已中止:无法创建SSL / TLS安全通道"
要解决此问题,可以在我的情况下更改Tls12的SecurityProtocol,并且运行良好。