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?
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):
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://americanexpress.com");
webRequest.AllowAutoRedirect = false;
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
int redirCount = 0;
while (webResponse.StatusCode == HttpStatusCode.TemporaryRedirect ||
webResponse.StatusCode == HttpStatusCode.MovedPermanently ||
webResponse.StatusCode == HttpStatusCode.MultipleChoices ||
webResponse.StatusCode == HttpStatusCode.Found ||
webResponse.StatusCode == HttpStatusCode.SeeOther)
{
string location = webResponse.Headers["Location"];
redirCount++;
Console.Out.WriteLine("Redirection location: {0}", location);
webRequest = (HttpWebRequest)WebRequest.Create(location);
webRequest.AllowAutoRedirect = false;
webResponse = (HttpWebResponse)webRequest.GetResponse();
}
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:
public class HttpWebRequestAdapter
{
private readonly HttpWebRequest _request;
public HttpWebRequestAdapter(HttpWebRequest request)
{
_request = request;
}
public int NumberOfRedirects
{
get
{
FieldInfo fi = _request.GetType().GetField("_AutoRedirects", BindingFlags.NonPublic | BindingFlags.Instance);
return (int)fi.GetValue(_request);
}
}
}
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://americanexpress.com");
webRequest.AllowAutoRedirect = true;
webRequest.MaximumAutomaticRedirections = 10;
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
HttpWebRequestAdapter adapter = new HttpWebRequestAdapter(webRequest);
Console.Out.WriteLine(adapter.NumberOfRedirects);
END EDIT
Hope, this helps.
精彩评论