【问题标题】:Why i'm getting exception: Too many automatic redirections were attempted on webclient?为什么我收到异常:在 webclient 上尝试了太多自动重定向?
【发布时间】:2014-10-30 13:31:50
【问题描述】:

在form1的顶部我做了:

WebClient Client;

然后在构造函数中:

Client = new WebClient();
Client.DownloadFileCompleted += Client_DownloadFileCompleted;
Client.DownloadProgressChanged += Client_DownloadProgressChanged;

然后我每分钟都会调用这个方法:

private void fileDownloadRadar()
        {
            if (Client.IsBusy == true)
            {
                Client.CancelAsync();
            }
            else
            {
                Client.DownloadProgressChanged += Client_DownloadProgressChanged;
                Client.DownloadFileAsync(myUri, combinedTemp);
            }
        }

每分钟它都会从网站下载一张图片,每次都是相同的图片。 直到现在在下载完成事件中抛出此异常之前,它都工作了 24 小时以上没有问题:

private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {

            if (e.Error != null)
            {
                timer1.Stop();
                span = new TimeSpan(0, (int)numericUpDown1.Value, 0);
                label21.Text = span.ToString(@"mm\:ss");
                timer3.Start();
            }
            else if (!e.Cancelled)
            {
                label19.ForeColor = Color.Green;
                label19.Text = "חיבור האינטרנט והאתר תקינים";
                label19.Visible = true;
                timer3.Stop();
                if (timer1.Enabled != true)
                {
                    if (BeginDownload == true)
                    {
                        timer1.Start();
                    }
                }                
                bool fileok = Bad_File_Testing(combinedTemp);
                if (fileok == true)
                {
                    File1 = new Bitmap(combinedTemp);
                    bool compared = ComparingImages(File1);
                    if (compared == false)
                    {

                        DirectoryInfo dir1 = new DirectoryInfo(sf);
                        FileInfo[] fi = dir1.GetFiles("*.gif");
                        last_file = fi[fi.Length - 1].FullName;
                        string lastFileNumber = last_file.Substring(82, 6);
                        int lastNumber = int.Parse(lastFileNumber);
                        lastNumber++;
                        string newFileName = string.Format("radar{0:D6}.gif", lastNumber);
                        identicalFilesComparison = File_Utility.File_Comparison(combinedTemp, last_file);
                        if (identicalFilesComparison == false)
                        {
                            string newfile = Path.Combine(sf, newFileName);
                            File.Copy(combinedTemp, newfile);
                            LastFileIsEmpty();
                        }
                    }
                    if (checkBox2.Checked)
                    {
                        simdownloads.SimulateDownloadRadar();
                    }
                }
                else
                {
                    File.Delete(combinedTemp);
                }
                File1.Dispose();
            }
        }

现在它在 if(e.Error != null) 内停止 上线:timer1.Stop();

然后我在错误中看到错误: 这是堆栈跟踪:

at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
   at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)

我怎样才能解决这个问题,这样它就不会再发生了?为什么会这样?

编辑:

我尝试将fileDownloadRadar方法改成这样,每次都释放客户端:

private void fileDownloadRadar()
        {
            using (WebClient client = new WebClient())
            {
                if (client.IsBusy == true)
                {
                    client.CancelAsync();
                }
                else
                {

                    client.DownloadFileAsync(myUri, combinedTemp);

                }
            }
        }

问题是在构造函数中我使用的是客户端,这里是客户端两个不同的 Webclient 变量。

我该如何解决这个问题和异常?

这是网站的网站墨水,其中包含我每分钟下载的图像。 仍然不确定为什么在它工作超过 24 小时没有问题后我得到这个异常。 现在我再次运行该程序并且它正在工作,但我想知道我是否会在明天或有时在接下来的几个小时内再次遇到此异常。

The site with image i'm downloading

【问题讨论】:

  • 更新了我的问题。我正在尝试与 Webclient 一起使用,但不确定这是异常的解决方案。第二个问题是如何使用 Using,因为现在我有两个不同的 WebClient 变量,这是错误的。
  • 您描述的错误与using无关。如果您想在类级别使用单个 WebClient 实例,则下载方法中不应包含 using 语句。你有没有看我的回答?

标签: c# .net winforms


【解决方案1】:

我在使用 WebClient 时遇到了同样的问题,并在这里找到了解决方案: http://blog.developers.ba/fixing-issue-httpclient-many-automatic-redirections-attempted/

使用 HttpWebRequest 并设置一个 CookieContainer 解决了这个问题,例如:

HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(linkUrl);
try
{
    webReq.CookieContainer = new CookieContainer();
    webReq.Method = "GET";
    using (WebResponse response = webReq.GetResponse())
    {
        using (Stream stream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(stream);
            res = reader.ReadToEnd();
            ...
        }
    }
}
catch (Exception ex)
{
    ...
}

【讨论】:

    【解决方案2】:

    如果您收到异常说明,说明重定向过多,这是因为您尝试访问的网站正在重定向到另一个站点,该站点正在指向另一个站点,然后是另一个站点,等等。默认重定向限制。

    因此,例如,您尝试从站点 A 获取图像。站点 A 将您重定向到站点 B。站点 B 将您重定向到站点 C,等等。

    WebClient 被配置为遵循重定向到某个默认限制。由于WebClient 是基于HttpWebRequest,它很可能使用MaximumAutomaticRedirections 的默认值,即50。

    很可能,服务器上存在错误并且它在一个紧密的循环中重定向,或者他们厌倦了你每分钟访问服务器一次相同的文件,他们是故意将您重定向到一个圆圈。

    确定实际情况的唯一方法是更改​​您的程序,使其不会自动跟随重定向。这样,您就可以检查网站返回的重定向 URL 并确定真正发生了什么。如果你想这样做,你需要使用HttpWebRequest 而不是WebClient

    或者,您可以使用 wget 之类的东西并打开详细日志记录。这将向您显示当您发出请求时服务器返回的内容。

    【讨论】:

      【解决方案3】:

      虽然这是一个老话题,但我不禁注意到发帖者使用的是 WebClient,它在发出请求时没有使用 UserAgent。许多网站会拒绝或重定向没有正确 UserAgent 字符串的客户端。

      考虑设置WebClient.Headers["User-Agent"]

      【讨论】:

      • 设置用户代理实际上对我有用。感谢您记住这一点。
      【解决方案4】:

      问题可以通过设置 cookie 容器来解决,最重要的是通过设置 webRequest.AllowAutoRedirect = false; 如下:

      HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
      webRequest.CookieContainer = new CookieContainer();
      webRequest.AllowAutoRedirect = false;
      

      【讨论】:

      【解决方案5】:

      我遇到了这个错误,但得到了一个简单的修复。

      您不需要所有代码,您只需在应用程序的开头下载这样的 cookie(抱歉,我使用 VB :) 但转换非常简单)

      [your application namespace].Application.GetCookie(New Uri("https://[site]"))
      

      【讨论】:

        【解决方案6】:

        最简单的方法是创建CookieAwareWebClient 并覆盖WebRequest 的创建。 看起来是这样的:

         public class CookieAwareWebClient : WebClient {
            public CookieContainer CookieContainer { get; set; }
            public Uri Uri { get; set; }
        
            public CookieAwareWebClient()
              : this(new CookieContainer()) {
            }
        
            public CookieAwareWebClient(CookieContainer cookies) {
              this.CookieContainer = cookies;
            }
        
            protected override WebRequest GetWebRequest(Uri address) {
              var request = base.GetWebRequest(address);
              if (request is HttpWebRequest) {
                (request as HttpWebRequest).CookieContainer = this.CookieContainer;
              }
        
              var httpRequest = (HttpWebRequest)request;
              httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
              httpRequest.AllowAutoRedirect = true;
              httpRequest.MaximumAutomaticRedirections = 100;
              httpRequest.ContinueTimeout = 5 * 60 * 1000;
              httpRequest.Timeout = 5 * 60 * 1000;
              return httpRequest;
            }
        
            protected override WebResponse GetWebResponse(WebRequest request) {
              var response = base.GetWebResponse(request);
              var setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];
        
              //if (setCookieHeader != null)
              //{
              //    Cookie cookie = new Cookie(); //create cookie
              //    cookie.Value = setCookieHeader;
              //    this.CookieContainer.Add(cookie);
              //}
              return response;
            }
         }
        

        【讨论】:

          【解决方案7】:

          这是@Ron.Eng 答案的VB.Net 版本:

          Public Function DownloadFileWithCookieContainerWebRequest(URL As String, FileName As String)
          
              Dim webReq As HttpWebRequest = HttpWebRequest.Create(URL)
              Try
          
                  webReq.CookieContainer = New CookieContainer()
                  webReq.Method = "GET"
                  Using response As WebResponse = webReq.GetResponse()
                      Using Stream As Stream = response.GetResponseStream()
                          Dim reader As StreamReader = New StreamReader(Stream)
                          Dim res As String = reader.ReadToEnd()
                          File.WriteAllText(FileName, res)
                      End Using
                  End Using
              Catch ex As Exception
                  Throw ex
              End Try
          
          End Function
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-01-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-31
            相关资源
            最近更新 更多