HTTPClient - 捕获所有重定向的列表 [英] HTTPClient - Capture a list of all Redirects

查看:30
本文介绍了HTTPClient - 捕获所有重定向的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to capture the full redirect history from a URL using HttpClient?

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

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?

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

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...

现在我假设以下内容:

    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) 捕获所有重定向.

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

这篇关于HTTPClient - 捕获所有重定向的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆