2015-12-22 142 views
1

偶尔会遇到“尝试尝试重定向太多”的例外情况。尝试使用WebRequest尝试抓取网页的HTML时,尝试使用WebRequest尝试使用太多重定向

这样的网站的一个例子是http://www.magicshineuk.co.uk/

通常我会设置超时时间为像6秒......但即使有30秒,最大重定向允许一些疯狂喜欢200,它仍然会抛出“太多重定向”异常,或者会发生超时。

我该如何解决这个问题?

我的代码如下...

try 
{ 

    System.Net.WebRequest request = System.Net.WebRequest.Create("http://www.magicshineuk.co.uk/"); 

    var hwr = ((HttpWebRequest)request); 

    hwr.UserAgent ="Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0"; 
    hwr.Headers.Add("Accept-Language", "en-US,en;q=0.5"); 
    hwr.Headers.Add("Accept-Encoding", "gzip, deflate"); 

    hwr.ContentType = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; ; 
    hwr.KeepAlive = true; 
    hwr.Timeout = 30000; // 30 seconds... normally set to 6000 
    hwr.Method = "GET"; 
    hwr.AllowAutoRedirect = true; 
    hwr.CookieContainer = new System.Net.CookieContainer(); 

    // Setting this Makes no difference... normally I would like to keep to a sensible maximum but I will leave as the default of 50 if needs be... 
    // Either way, the Too Many Redirections exception occurs 
    hwr.MaximumAutomaticRedirections = 200; 

    using (var response = (HttpWebResponse)hwr.GetResponse()) 
    { 

     Console.WriteLine(String.Format("{0} {1}", (int)response.StatusCode, response.StatusCode)); 
     Console.WriteLine(response.ResponseUri); 
     Console.WriteLine("Last modified: {0}", response.LastModified); 
     Console.WriteLine("Server: {0}", response.Server); 
     Console.WriteLine("Supports Headers: {0}", response.SupportsHeaders); 
     Console.WriteLine("Headers: "); 

     // do something... e.g: 
     int keyCount = response.Headers.Keys.Count; 
     int i = 0; 
     Dictionary<string, string> hc = new Dictionary<string, string>(); 
     foreach (var hname in response.Headers) 
     { 
      var hv = response.Headers[i].ToString(); 
      hc.Add(hname.ToString(), hv); 
      i++; 
     } 
     foreach (var di in hc) 
     { 
      Console.WriteLine(" {0} = {1}", di.Key, di.Value); 
     } 

    } 


} 
catch (Exception ex) 
{ 
    Console.WriteLine("Exception: "); 
    Console.WriteLine(ex.Message); 
} 

回答

2

我想你的代码,我需要注释掉// hwr.Host = Utils.GetSimpleUrl(url);它工作得很好。如果您经常进行轮询,那么目标站点或两者之间(代理,防火墙等)可能会将您的轮询视为拒绝服务,并将您定时计时一段时间。或者,如果您位于公司防火墙的后面,则可能会收到与内部网络设备类似的警告。

你多久运行一次这个刮刀?

编辑补充:

  • 这个我试过使用.NET 4.52,Windows 7的64位时,Visual Studio 2015年

  • 目标网站也可能是不可靠的(上下)

  • 您和目标网站之间可能存在间歇性网络问题
  • 它们可能会暴露一个API,这将是一个更可靠的集成
+0

我的错。你删除的线是罪魁祸首!我的函数“GetSimpleUrl(url)”返回“magicshineuk.co.uk”,因此重定向是因为主机在请求发生前被设置。代码现在实际运行良好。 – collumbo

+0

为了记录,我删除了行hwr.Host = Utils.GetSimpleUrl(url);以避免混淆。这些代码现在适合其他人使用。 – collumbo

+0

FTW!很高兴现在排序。 –