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个方法isRedirected
和getRedirect
在您的情况下,您可以通过以下方式获取所有重定向:
final HttpClientContext clientContext = HttpClientContext.adapt(context); RedirectLocations redirectLocations = (RedirectLocations) clientContext.getAttribute( HttpClientContext.REDIRECT_LOCATIONS );
您可以在getRedirect
添加此代码。 这也可以在DefaultRedirectStrategy
类的getLocationURI
方法中找到此代码。
- Android TestSuite:包括除明确定义的所有TestCase之外的所有TestCase
- 在使用Spring MVC和Spring Security @PreAuthorize注释时,是否可以知道URL是否可访问?
- Apache HTTPClient SSLPeerUnverifiedException
- 在HTTPClient 4.1中使用文件和字符串进行多部分POST
- Peer未在java中进行身份validation
- HTTPSURLconnection和Apache(系统)DefaultHttpClient之间的证书链不同
- 如何在HttpClient的请求中添加,设置和获取Header?
- java.io.IOException:尝试从封闭流中读取
- SSLHandshakeException:证书中的主机名不匹配
- Apache PoolingHttpClientConnectionManager抛出非法状态exception
- 配置Apache HttpClient通过代理/负载均衡器访问服务(覆盖主机头)