无法使用HttpWebRequest下载一些https主页

时间:2016-04-17 11:39:15

标签: c# ssl httpwebrequest

我只是尝试使用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;
}

亲切的问候

1 个答案:

答案 0 :(得分:0)

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