【问题标题】:HTTPS Urls using the WebDownloadClient throws an exception使用 WebDownloadClient 的 HTTPS Urls 引发异常
【发布时间】:2015-08-06 03:29:48
【问题描述】:

我有一个引发以下异常的 https URL:

异常详细信息:System.Exception:底层连接是 关闭:发送时发生意外错误。 ---> System.Net.WebException:底层连接已关闭:一个 发送时发生意外错误。 ---> System.IO.IOException: 从传输流中接收到意外的 EOF 或 0 字节。

我尝试使用 URL 的 HTTP 版本,并且可以正常工作。我还检查了是否可以从机器访问 https URL,并且可以在没有任何错误的情况下访问它们,但是在下面的代码中失败了。这个问题也是特定于机器的。

代码行抛出错误:

 using (WebDownloadClient wc = new WebDownloadClient())
 {
     wc.Headers.Add("Content-Encoding", "gzip");
     wc.Headers.Add("Accept-Encoding", "gzip, compress");
     wc.DownloadFile(url, fileName);
 }

【问题讨论】:

标签: c# .net https


【解决方案1】:
    ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 ;

    using (WebDownloadClient wc = new WebDownloadClient())
    {
        wc.Headers.Add("Content-Encoding", "gzip");
        wc.Headers.Add("Accept-Encoding", "gzip, compress");
        wc.DownloadFile(url, fileName);
    }

private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
    if (error == System.Net.Security.SslPolicyErrors.None)
    {
        return true;
    }
    return false;
}

取自Requesting html over https with c# Webclient

【讨论】:

  • 我在代码中看到了下面一行。这是否强制仅使用有效证书? ServicePointManager.CertificatePolicy = new CertificatePolicy();
  • 当 CertificatePolicy 属性设置为 ICertificatePolicy 接口对象时,ServicePointManager 对象使用该实例中定义的证书策略而不是默认证书策略。默认证书策略允许有效证书和已过期的有效证书。
  • 谢谢@HyunMi。我还在 m/c 上观察到,我可以在浏览器中访问 https URL,但通过代码我得到了上述异常。
猜你喜欢
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-25
相关资源
最近更新 更多