gpt4 book ai didi

c# - 无法使用 HttpWebRequest 下载某些 https 主页

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:02 26 4
gpt4 key购买 nike

我只是想使用 C# 从各种零售站点下载一些站点信息,只是主页的纯 HTML。我在某些使用 https 的网站上遇到问题,有些网站工作正常,而对于其他网站,我遇到以下异常

The underlying connection was closed: An unexpected error occurred on a send.

内部异常有

The handshake failed due to an unexpected packet format.

我认为它与 TLS 有关,但对于我的生活我无法弄清楚。我一直在研究 Stack Overflow 和 HttpWebRequest 文档。

下面是我用来调用网站的示例代码,如果有人对此有任何见解,我将不胜感激,这让我发疯。

public HttpWebResponse GetWebResponse(HtmlVerb verb, Uri uri)
{

var request = System.Net.WebRequest.CreateHttp(uri);
request.Method = verb.ToString();
request.ProtocolVersion = HttpVersion.Version11;
request.CookieContainer = new CookieContainer();
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0";
request.Timeout = (int)TimeSpan.FromSeconds(10).TotalMilliseconds;
request.AllowAutoRedirect = true;
request.ServerCertificateValidationCallback = delegate { return true; };
request.Headers.Add("Accept-Language", "en-US,en;q=0.5");
request.Headers.Add("Accept-Encoding", "gzip, deflate");
request.ContentType = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.KeepAlive = false;

return request.GetResponse() as HttpWebResponse;
}

亲切的问候

最佳答案

对于遇到此问题的任何其他人,我发现以下解决方案有效。如果您在应用程序的开头包含以下代码行以初始化应用程序上下文,那么这些现在使用 https 的问题站点将正确下载。

private const string DisableCachingName = @"TestSwitch.LocalAppContext.DisableCaching";
private const string DontEnableSchUseStrongCryptoName = @"Switch.System.Net.DontEnableSchUseStrongCrypto";
static void Main(string[] args)
{
AppContext.SetSwitch(DisableCachingName, true);
AppContext.SetSwitch(DontEnableSchUseStrongCryptoName, false);

关于c# - 无法使用 HttpWebRequest 下载某些 https 主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36676002/

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