问题
Is it possible to capture the full redirect history from a URL using HttpClient?
Say for example we have URL-A which redirects to URL-B which finally sends us to URL-C, is there a way to capture what URLs A, B and C were?
The most obvious option is to manually look for the location tag in the header, and stop when we reach a HTTP 200. This isnt a simple process as we would need to look for circular redirects etc etc...
Now I'm assuming the something along the lines of:
HttpContext context = new BasicHttpContext();
HttpResponse response = hc.execute(httpget, context);
//.....
for(URI u : ((RedirectLocations)context.getAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS)).getAll()){
System.out.println(u);
}
will work for this use case?
回答1:
HttpClient supports custom RedirectHandler. You can override the default implementation (DefaultRedirectHandler) to capture all the redirects.
DefaultHttpClient hc = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://google.com");
HttpContext context = new BasicHttpContext();
hc.setRedirectHandler(new DefaultRedirectHandler() {
@Override
public URI getLocationURI(HttpResponse response,
HttpContext context) throws ProtocolException {
//Capture the Location header here
System.out.println(Arrays.toString(response.getHeaders("Location")));
return super.getLocationURI(response,context);
}
});
HttpResponse response = hc.execute(httpget, context);
回答2:
RedirectHandler
is deprecated as of 4.1
RedirectStrategy
is to be used.
we can override 2 methods isRedirected
and getRedirect
In your case you can get all redirects by:
final HttpClientContext clientContext =
HttpClientContext.adapt(context);
RedirectLocations redirectLocations = (RedirectLocations)
clientContext.getAttribute(
HttpClientContext.REDIRECT_LOCATIONS
);
You can add this code in getRedirect
. This can also find this code in getLocationURI
method of DefaultRedirectStrategy
class.
来源:https://stackoverflow.com/questions/7860188/httpclient-capture-a-list-of-all-redirects