【问题标题】:Cannot download some https home pages using HttpWebRequest无法使用 HttpWebRequest 下载某些 https 主页
【发布时间】:2016-04-17 11:39:14
【问题描述】:

我只是想从各种使用 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;
}

亲切的问候

【问题讨论】:

标签: c# ssl httpwebrequest


【解决方案1】:

对于遇到此问题的其他人,我发现以下解决方案可行。 如果您在应用程序的开头包含以下代码行来初始化应用程序上下文,那么这些使用 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);

【讨论】:

    猜你喜欢
    • 2019-12-26
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多