Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c# - Why i'm getting exception: Too many automatic redirections were attempted on webclient?

In the top of form1 i did:

WebClient Client;

Then in the constructor:

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

Then i have this method i'm calling every minute:

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

Every minutes it's downloading an image from a website same image each time. It was all working for more then 24 hours no problems untill now throwing this exception in the download completed event:

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

Now it stopped inside the if(e.Error != null) On the line: timer1.Stop();

Then i see on the Error the error: This is the stack trace:

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

How can i solve this problem so it won't happen again ? And why it happened ?

EDIT:

I tried to change the fileDownloadRadar method to this to release the client every time:

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

                    client.DownloadFileAsync(myUri, combinedTemp);

                }
            }
        }

The problem is that in the constructor i'm using Client and here it's client two different Webclient variables.

How can i solve this and the exception ?

This is the websitel ink for the site with the image i'm downloading every minute. Still not sure yet why i got this exception after it was working no problems for more then 24 hours. Now i ran the program again over again and it's working but i wonder if i will get this exception again tommorow or sometimes in the next hours.

The site with image i'm downloading

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same problem with WebClient and found the solution here: http://blog.developers.ba/fixing-issue-httpclient-many-automatic-redirections-attempted/

Using HttpWebRequest and setting a CookieContainer solved the problem, for example:

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)
{
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...