C# System.Net.WebException: 'Too many automatic redirections were attempted.'

C# System.Net.WebException: 'Too many automatic redirections were attempted.'

我想使用 webclient 下载一个 68kb 的 zip 文件,但出现错误: C# System.Net.WebException: 'Too many automatic redirections were attempted.'

关于这个 post 是重复的 post: 解决方案解释于:Why i'm getting exception: Too many automatic redirections were attempted on webclient? 不要让我的代码在下面工作并下载 zip 文件。 我如何编辑才能更好地解释?

我的代码:

var url_from = "http://www1.caixa.gov.br/listaweb/Lista_imoveis_RJ.zip";
            var _to = @"F:\folder\file.zip";

            using (var client = new WebClient())
            {
                client.DownloadFile(url_from, _to);
            }

我也尝试过异步方式,但生成的是空 zip 文件。 像这样:How do I download zip file in C#? 还有这个:

这是由错误的服务器实现引起的。如果您使用 Fiddler,您会看到服务器将 HTTPS 和 HTTP 连接重定向到 相同的 HTTP url,添加一个 security=true cookie。

通过 HTTP 调用特别有趣:

  1. 第一个 HTTP 重定向到 HTTPS URL
  2. HTTPS 使用 security=true cookie
  3. 重定向回原始 HTTP
  4. 如果 cookie 不存在,循环将再次开始

这意味着:

  • 没有安全保障。任何东西都可以拦截该调用并更改或替换文件的内容。希望您不要尝试通过 WiFi 下载此文件!
  • 除非您存储 cookie 或自行添加,否则服务器将导致无限重定向循环。

WebClient 无法存储 cookie。这是一个过时的 class 创建回来时下载页面和文件是所有需要的。 HttpClient class 提供了它的所有功能以及更多功能。

虽然在这种情况下,您可以自己将 cookie 添加为 header 并避免重定向,并且 仍然 通过 HTTPS 下载文件

WebClient 已过时 class。它是为简单的文件和页面请求而创建的,

var url_from = "https://www1.caixa.gov.br/listaweb/Lista_imoveis_RJ.zip";
using (var client = new System.Net.WebClient())
{
    client.Headers.Add(System.Net.HttpRequestHeader.Cookie, "security=true");
    client.DownloadFile(url_from, _to);
}

这将导致一次调用并通过 HTTP 下载文件