HttpClient 4 - 如何捕获上次重定向 URL [英] HttpClient 4 - how to capture last redirect URL

查看:35
本文介绍了HttpClient 4 - 如何捕获上次重定向 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有相当简单的 HttpClient 4 代码,它调用 HttpGet 来获取 HTML 输出.HTML 返回的脚本和图像位置都设置为本地(例如 <img src="/images/foo.jpg"/>),所以我需要调用 URL 使它们成为绝对的(<img src="http://foo.com/images/foo.jpg"/>) 现在问题来了——在调用过程中可能会有一两个 302 重定向,所以原始 URL不再反映 HTML 的位置.

I have rather simple HttpClient 4 code that calls HttpGet to get HTML output. The HTML returns with scripts and image locations all set to local (e.g. <img src="/images/foo.jpg"/>) so I need calling URL to make these into absolute (<img src="http://foo.com/images/foo.jpg"/>) Now comes the problem - during the call there may be one or two 302 redirects so the original URL is no longer reflects the location of HTML.

考虑到我可能(或可能没有)拥有的所有重定向,我如何获取返回内容的最新 URL?

How do I get the latest URL of the returned content given all the redirects I may (or may not) have?

我查看了 HttpGet#getAllHeaders()HttpResponse#getAllHeaders() - 找不到任何东西.

I looked at HttpGet#getAllHeaders() and HttpResponse#getAllHeaders() - couldn't find anything.

HttpGet#getURI() 返回原始调用地址

推荐答案

那将是当前的 URL,您可以通过调用

That would be the current URL, which you can get by calling

  HttpGet#getURI();

您没有提到您如何进行重定向.这对我们有用,因为我们自己处理 302.

You didn't mention how you are doing redirect. That works for us because we handle the 302 ourselves.

听起来您正在使用 DefaultRedirectHandler.我们曾经这样做过.获取当前 URL 有点棘手.您需要使用自己的上下文.以下是相关的代码片段,

Sounds like you are using DefaultRedirectHandler. We used to do that. It's kind of tricky to get the current URL. You need to use your own context. Here are the relevant code snippets,

        HttpGet httpget = new HttpGet(url);
        HttpContext context = new BasicHttpContext(); 
        HttpResponse response = httpClient.execute(httpget, context); 
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
            throw new IOException(response.getStatusLine().toString());
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute( 
                ExecutionContext.HTTP_REQUEST);
        HttpHost currentHost = (HttpHost)  context.getAttribute( 
                ExecutionContext.HTTP_TARGET_HOST);
        String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());

默认重定向对我们不起作用,所以我们进行了更改,但我忘记了问题所在.

The default redirect didn't work for us so we changed but I forgot what was the problem.

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

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