使用c#Webclient通过https请求html

我正在通过c#WebClient类从我无法控制的站点尝试各种html资源。 当我尝试访问“ https://archive.org/details/OTRR_In_The_Name_Of_The_Law_Singles ”等url时

我收到错误:System.Net.WebException:请求已中止:无法创建SSL / TLS安全通道。

我找到的解决方案建议我使用以下代码忽略证书要求并使webclient充当浏览器,但我仍然收到相同的错误

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。

在通话中添加以下行:

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; 

这是一个完整的例子:

 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(); } } } ///  /// Certificate validation callback. ///  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中添加

 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2 

只需在var stream = webClient.OpenRead(address);之前添加这一行var stream = webClient.OpenRead(address);

 System.Net.ServicePointManager.ServerCertificateValidationCallback += (send, certificate, chain, sslPolicyErrors) => { return true; }; 

这应该解决SSL / TLS错误