简体   繁体   中英

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

I want to download a 68kb zip file using webclient and I have the error: C# System.Net.WebException: 'Too many automatic redirections were attempted.'

About this post is a duplicated post: The solution explained in: Why i'm getting exception: Too many automatic redirections were attempted on webclient? Don't work to make my code below works and download the zip file. How Can I edit to explain better ?

My code:

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);
            }

I tried Async ways too but it was generated empty zip file. Like this: How do I download zip file in C#? and this: How can I download a ZIP file from a URL using C#?

This is caused by a bad server implementation. If you use Fiddler, you'll see that the server redirects both HTTPS and HTTP connections to the same HTTP url, adding a security=true cookie.

Calling over HTTP is particulary funny :

  1. The first HTTP redirects to an HTTPS URL
  2. The HTTPS redirects back to the original HTTP with the security=true cookie
  3. If the cookie isn't there, the loop starts again

This means that :

  • There's no security. Anything can intercept that call and alter or replace the contents of the file. Hope you don't try to download this file over WiFi!
  • The server will cause an infinite redirection loop unless you store the cookie or add it yourself.

WebClient can't store cookies. It's an obsolete class created back when downloading pages and files was all that's needed. All of its functionality and much more is provided by the HttpClient class.

In this case though, you can add the cookie as a header yourself and avoid the redirections, and still download the file over HTTPS

WebClient is an obsolete class. It was created for simple file and page requests and

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);
}

This will result in a single call and download the file over HTTP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM