使用WebRequest尝试了太多重定向
本文关键字:太多 重定向 WebRequest 使用 | 更新日期: 2023-09-27 18:27:42
当试图获取网页的html时,偶尔会出现异常"尝试了太多重定向"。
这样一个网站的例子是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);
}
我尝试了您的代码,需要注释掉// hwr.Host = Utils.GetSimpleUrl(url);
,它运行得很好。如果你经常进行轮询,那么目标站点或介于两者之间的东西(代理、防火墙等)可能会将你的轮询识别为拒绝服务,并将你超时一段时间。或者,如果你在公司防火墙后面,你可能会收到来自内部网络设备的类似信息。
你多久运行一次这台刮刀?
编辑后添加:
-
我使用.net 4.52、Windows 7 x64、Visual Studio 2015 进行了尝试
-
目标站点也可能是不可靠的(上下)
- 您和目标站点之间可能存在间歇性网络问题
- 他们可能会公开一个API,这将是一个更可靠的集成