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

编程入门 行业动态 更新时间:2024-10-26 16:28:53
本文介绍了从https URL下载文件时出现WebClient错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

尝试从https URL下载XML文件( nvd.nist.gov /download/nvd-rss.xml )

Trying to download xml file from https URL (nvd.nist.gov/download/nvd-rss.xml)

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

This URL is openly accessible through browser.

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

Using C# Webclient with console project.

但是出现如下所示的异常

But getting Exception as below

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

$ exception {基础连接已关闭: send。} System.Net.WebException

$exception {"The underlying connection was closed: An unexpected error occurred on a send."} System.Net.WebException

试图将所有类似SSL的属性添加到system.Net,但没有帮助。

Tried adding all properties like SSL etc to system.Net, but did not help.

推荐答案

原因是相关站点仅支持TLS 1.2。在.NET中, System.Net.ServicePointManager.SecurityProtocol 的默认值为 Ssl | Tls ,这意味着默认情况下.NET客户端不支持Tls 1.2(在SSL协商期间,它不在支持的协议列表中列出该协议)。至少对于许多.NET Framework版本都是这种情况,不确定是否全部适用。但是.NET实际上确实支持TLS 1.2,要启用它,您应该这样做:

The reason is site in question supports only TLS 1.2. In .NET, default value for System.Net.ServicePointManager.SecurityProtocol is Ssl | Tls, which means that .NET client by default does not support Tls 1.2 (it does not list this protocol in the list of supported protocols during SSL negotiation). At least this is the case for many .NET Framework versions, not sure if for all. But .NET really do support TLS 1.2, and to enable it you should just do:

string uri = "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:

And you should be fine. Of course it's better to support more than one TLS 1.2 protocol, because System.Net.SecurityProtocolType is a global setting and not all sites support TLS 1.2:

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

更多推荐

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

本文发布于:2023-11-05 04:40:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   文件   https   URL   WebClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!