2015-12-22 143 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!很高興現在排序。 –