循环下载的C#Webclient问题?

时间:2010-01-23 12:15:42

标签: c# webclient

这是我对Webclient的实现,据说,这个下载应该是连续的,但由于某些原因,哪个调试甚至没有帮助,我在第一次运行中获得1次成功,然后其余的都失败了。有谁知道为什么?

        for (int i = 1; i <= Count; i++)
        {
            using (WebClient wc = new WebClient())
            {

                wc.Headers["Accept-Encoding"] = "gzip";
                wc.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                byte[] arr = wc.DownloadData(url);

                if (arr.Length > 0)
                    Console.WriteLine(i.ToString() + ": SUCCESS");
                else
                    Console.WriteLine(i.ToString() + ": FAILED");
            }

        }

2 个答案:

答案 0 :(得分:1)

当我搞砸了这段代码时,它很有用,哈哈!我不知道该说些什么......

                using (WebClient client = new WebClient())
                {
                    //manipulate request headers (optional)
                    client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

                    //execute request and read response as string to console
                    using (StreamReader reader = new StreamReader(client.OpenRead(url)))
                    {
                        string s = reader.ReadToEnd();
                        //Console.WriteLine(s);
                        Console.WriteLine("Vote " + i.ToString() + ": SUCCESS");
                        i++;
                    }
                }

                // *** Establish the request
                HttpWebRequest loHttp =
                     (HttpWebRequest)WebRequest.Create(url);

                // *** Set properties
                loHttp.Timeout = 10000;     // 10 secs
                loHttp.UserAgent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                loHttp.Headers["Accept-Encoding"] = "gzip";
                // *** Retrieve request info headers
                HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();

                Encoding enc = Encoding.GetEncoding(1252);  // Windows default Code Page

                StreamReader loResponseStream =
                   new StreamReader(loWebResponse.GetResponseStream(), enc);

                string lcHtml = loResponseStream.ReadToEnd();

                loWebResponse.Close();
                loResponseStream.Close();

                if (lcHtml.Length > 0)
                {
                    Console.WriteLine("Vote " + i.ToString() + ": SUCCESS");
                    i++;
                }
                else
                    Console.WriteLine("Vote " + i.ToString() + ": FAILED");
            }

标记为社区维基,如果有人知道原因,请编辑... :(

答案 1 :(得分:0)

使用像Fiddler这样的调试代理,您将能够看到HTTP事务。

相关问题