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

查看:488
本文介绍了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.

如果我可能(或可能不)拥有所有重定向,我如何获得返回内容的最新网址?

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()返回原始呼叫地址

Edited: HttpGet#getURI() returns original calling address

推荐答案

这将是当前的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天全站免登陆