1

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

例如,我们有 URL-A 重定向到 URL-B,最终将我们发送到 URL-C,有没有办法捕获 URL A、B 和 C 是什么?

最明显的选择是手动查找标头中的位置标记,并在达到 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);
    }

将适用于这个用例吗?

4

2 回答 2

3

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);
于 2011-10-22T15:37:29.563 回答
0

RedirectHandler从 4.1 RedirectStrategy开始不推荐使用。

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

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

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

于 2018-07-27T06:57:22.453 回答