HTTPClient – 捕获所有重定向的列表

是否可以使用HttpClient从URL捕获完整的重定向历史记录?

比方说,我们有URL-A重定向到URL-B,它最终将我们发送到URL-C,有没有办法捕获A,B和C的URL?

最明显的选择是在标题中手动查找位置标记,并在到达HTTP 200时停止。这不是一个简单的过程,因为我们需要查找循环重定向等等…

现在我假设的东西是这样的:

HttpContext context = new BasicHttpContext(); HttpResponse response = hc.execute(httpget, context); //..... for(URI u : ((RedirectLocations)context.getAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS)).getAll()){ System.out.println(u); } 

将适用于此用例?

HttpClient支持自定义RedirectHandler 。 您可以覆盖默认实现( DefaultRedirectHandler )以捕获所有重定向。

 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); 

RedirectHandler自4.1开始不推荐使用RedirectStrategy

我们可以覆盖2个方法isRedirectedgetRedirect在您的情况下,您可以通过以下方式获取所有重定向:

 final HttpClientContext clientContext = HttpClientContext.adapt(context); RedirectLocations redirectLocations = (RedirectLocations) clientContext.getAttribute( HttpClientContext.REDIRECT_LOCATIONS ); 

您可以在getRedirect添加此代码。 这也可以在DefaultRedirectStrategy类的getLocationURI方法中找到此代码。