【问题标题】:Getting redirected URL in Apache HttpComponents在 Apache HttpComponents 中获取重定向的 URL
【发布时间】:2012-06-25 22:48:06
【问题描述】:

我正在使用Apache HttpComponents 获取一些网页以获取一些已抓取的 URL。其中许多 URL 实际上重定向到不同的 URL(例如,因为它们已使用 URL 缩短器进行处理)。除了下载内容之外,我还想解析最终 URL(即提供下载内容的 URL),甚至更好的是,重定向链中的所有 URL。

我一直在查看 API 文档,但不知道在哪里可以挂钩。任何提示将不胜感激。

【问题讨论】:

    标签: java url redirect apache-httpcomponents


    【解决方案1】:

    这里是a full demo,说明如何使用 Apache HttpComponents。

    重要细节

    您需要像这样扩展DefaultRedirectStrategy

    class SpyStrategy extends DefaultRedirectStrategy {
        public final Deque<URI> history = new LinkedList<>();
    
        public SpyStrategy(URI uri) {
            history.push(uri);
        }
    
        @Override
        public HttpUriRequest getRedirect(
                HttpRequest request,
                HttpResponse response,
                HttpContext context) throws ProtocolException {
            HttpUriRequest redirect = super.getRedirect(request, response, context);
            history.push(redirect.getURI());
            return redirect;
        }
    }
    

    expand 方法发送一个 HEAD 请求,导致 client 收集 spy.history deque 中的 URI,因为它会自动跟随重定向:

    public static Deque<URI> expand(String uri) {
        try {
            HttpHead head = new HttpHead(uri);
            SpyStrategy spy = new SpyStrategy(head.getURI());
            DefaultHttpClient client = new DefaultHttpClient();
            client.setRedirectStrategy(spy);
            // FIXME: the following completely ignores HTTP errors:
            client.execute(head);
            return spy.history;
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    

    您可能希望将重定向的最大数量设置为合理的值(而不是默认值 100),如下所示:

            BasicHttpParams params = new BasicHttpParams();
            params.setIntParameter(ClientPNames.MAX_REDIRECTS, 5);
            DefaultHttpClient client = new DefaultHttpClient(params);
    

    【讨论】:

    • 哇,已经有一段时间了,但是在 HttpComponents 更新后长期需要的重构过程中,我集成了您的解决方案并且效果很好。谢谢!
    【解决方案2】:

    一种方法是通过设置 relevant parameter 来关闭自动重定向处理,并通过检查 3xx 响应并从响应的“Location”标头中手动提取重定向位置来自行完成。

    【讨论】:

    • 谢谢,是不是像你建议的那样。有效!
    猜你喜欢
    • 1970-01-01
    • 2014-04-16
    • 2013-06-29
    • 2011-08-17
    • 1970-01-01
    • 2013-09-07
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多