从https URL下载文件时出现WebClient错误

时间:2016-09-03 13:53:56

标签: c# https console-application webclient downloadfile

尝试从https网址(https://nvd.nist.gov/download/nvd-rss.xml

下载xml文件

此网址可通过浏览器公开访问。

将C#Webclient与控制台项目一起使用。

但是如下所示得到例外

    using (WebClient client = new WebClient())
    {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3;
            client.DownloadFile(uri, @"c:\test\nvd-rss.xml");
    }

$ exception {"基础连接已关闭:发送时发生意外错误。"} System.Net.WebException

尝试将所有属性(如SSL等)添加到system.Net,但没有帮助。

3 个答案:

答案 0 :(得分:18)

原因是有问题的网站仅支持TLS 1.2。在.NET中,System.Net.ServicePointManager.SecurityProtocol的默认值为Ssl | Tls,这意味着默认情况下.NET客户端不支持Tls 1.2(它在SSL协商期间不会在支持的协议列表中列出此协议)。至少对于许多.NET Framework版本来说就是这种情况,不确定是否适用于所有版本。但是.NET确实支持TLS 1.2,为了实现它你应该这样做:

string uri = "https://nvd.nist.gov/download/nvd-rss.xml";
using (WebClient client = new WebClient())
{
     System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
     client.DownloadFile(uri, @"c:\test\nvd-rss.xml");
}

你应该没事。 当然,支持多个TLS 1.2协议会更好,因为System.Net.SecurityProtocolType是一个全局设置,并非所有站点都支持TLS 1.2:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

答案 1 :(得分:3)

.NET 4.0。不支持TLS 1.2,但是如果您在系统上安装了.NET 4.5(或更高版本),那么即使您的应用程序框架不支持TLS 1.2,您仍然可以选择使用TLS 1.2。唯一的问题是.NET 4.0中的SecurityProtocolType没有TLS1.2的条目,因此我们必须使用此枚举值的数字表示形式:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

答案 2 :(得分:1)

试试这个:

using (HttpClient client = new HttpClient())
{
      var response = await client.GetAsync("https://nvd.nist.gov/download/nvd-rss.xml");

      string xml = await response.Content.ReadAsStringAsync();
      //or as byte array if needed
      var xmlByteArray = await response.Content.ReadAsByteArrayAsync();
      //or as stream
      var xmlStream = await  response.Content.ReadAsStreamAsync();

      //write to file
       File.WriteAllBytes(@"c:\temp\test.xml", xmlByteArray)

 }