HttpWebRequest.AllowAutoRedirect = false可能导致超时? [英] HttpWebRequest.AllowAutoRedirect=false can cause timeout?

查看:221
本文介绍了HttpWebRequest.AllowAutoRedirect = false可能导致超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试约300网址来验证他们是否导致实际的页面或重定向到其他页面。我在.NET 2.0编写了一个简单的应用程序来检查它,使用HttpWebRequest的。这里的code片断:

I need to test around 300 URLs to verify if they lead to actual pages or redirect to some other page. I wrote a simple application in .NET 2.0 to check it, using HttpWebRequest. Here's the code snippet:

System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create( url );
System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)wr.GetResponse();
code = resp.StatusDescription;

code跑得飞快,写到文件,我所有的网址返回状态200确定。后来我意识到,在默认情况下的GetResponse()遵循重定向。我傻!所以我加了一条线,使其正常工作:

Code ran fast and wrote to file that all my urls return status 200 OK. Then I realized that by default GetResponse() follows redirects. Silly me! So I added one line to make it work properly:

System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create( url );
wr.AllowAutoRedirect = false;
System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)wr.GetResponse();
code = resp.StatusDescription;

我再次运行程序,等待着......等待着......等待着......原来,每个网址我得到一个System.Net.WebException操作超时。惊讶,我手动检查URL - 工作正常......我注释掉AllowAutoRedirect =错误路线 - 并能正常工作了。取消注释该行 - 超时。任何想法可能会导致这样的问题,如何解决?

I ran the program again and waited... waited... waited... It turned out that for each url I was getting a System.Net.WebException "The operation has timed out". Surprised, I checked the URL manually - works fine... I commented out AllowAutoRedirect = false line - and it works fine again. Uncommented this line - timeout. Any ideas what might cause this problem and how to work around?

推荐答案

经常超时是由于没有被设置的网络响应。你应该有一个使用语句的 HttpWebResponse

Often timeouts are due to web responses not being disposed. You should have a using statement for your HttpWebResponse:

using (HttpWebResponse resp = (HttpWebResponse)wr.GetResponse())
{
    code = resp.StatusDescription;
    // ...
}

我们就需要做更多的分析,以predict不管是肯定的问题... ...或者你可以试试吧:)

We'd need to do more analysis to predict whether that's definitely the problem... or you could just try it :)

原因是,.NET有一个连接池,如果你不关闭响应,不返回连接池(至少在GC定型的响应)。这导致挂起请求时,等待连​​接。

The reason is that .NET has a connection pool, and if you don't close the response, the connection isn't returned to the pool (at least until the GC finalizes the response). That leads to a hang while the request is waiting for a connection.

这篇关于HttpWebRequest.AllowAutoRedirect = false可能导致超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆