确定 HttpWebRequest 发出的总请求数,包括重定向
我想以编程方式为资源构造 HttpWebRequest,不仅获取 HttpWebResponse,还确定为成功返回响应而发出的 HTTP 请求总数。
例如,如果我请求 http://americanexpress.com 我将被重定向 3 次最终响应:
在此示例中,总共发出了 4 个请求。默认情况下,HttpWebRequest 将AllowAutoRedirect 设置为true,以便任何导致重定向的响应(例如HTTP 301)将自动发出另一个请求。这很好,我只是想知道发出了多少个请求。
除了将AllowAutoRedirect设置为false并通过重建请求手动响应重定向之外,有什么方法可以做到这一点吗?
I want to programmatically construct an HttpWebRequest for a resource and not just get the HttpWebResponse, but also determine the total number of HTTP requests made to successfully return the response.
For example, if I make a request for http://americanexpress.com I'm going to get redirected 3 times before the final response:
In this example, there are a total of 4 requests being made. By default, HttpWebRequest sets AllowAutoRedirect to true so any response causing a redirect - such as an HTTP 301 - will automatically issue another request. This is fine, I just want to know how many requests were issued.
Is there any way to do this short of setting AllowAutoRedirect to false and manually responding to a redirect by reconstructing requests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过将AllowAutoRedirect 设置为 false 并响应 HTTP 重定向状态代码来实现此目的。有关 HTTP 状态代码的完整列表,请参阅 W3C。这是一个小代码示例(省略了错误处理详细信息):
编辑:
我刚刚意识到有一个名为 MaximumAutomaticRedirections 的属性
HttpWebRequest 类。因此,HttpWebRequest 类必须计算
重定向以处理允许的最大重定向。我已经调试到
HttpWebRequest类的源代码,发现一个名为_AutoRedirections的私有字段
它计算重定向的次数。
因此,要获取重定向的数量,一个更简单的解决方案是:
END EDIT
希望这会有所帮助。
You can achieve this by setting AllowAutoRedirect to false and responding to HTTP redirect status codes. For a complete list of HTTP status code see W3C. Here is a small code example (error handling details omitted):
EDIT:
I just realized that there is a property called MaximumAutomaticRedirections on the
HttpWebRequest class. So, the HttpWebRequest class must count the number of
redirections to handle the maximum allowed redirections. I've debugged into the
source code of the HttpWebRequest class and found a private field called _AutoRedirections
which counts the number of redirections.
So, to get the number of redirections a much simpler solution would be:
END EDIT
Hope, this helps.