gpt4 book ai didi

c# - 使用 c# Webclient 通过 https 请求 html

转载 作者:可可西里 更新时间:2023-11-01 07:50:17 24 4
gpt4 key购买 nike

我正在尝试通过 c# WebClient 类从我无法控制的站点获取各种 html 资源。当我尝试访问诸如"https://archive.org/details/OTRR_In_The_Name_Of_The_Law_Singles "

我得到错误: 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();
}
}
}

/// <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;
}

关于c# - 使用 c# Webclient 通过 https 请求 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20064505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com