52

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

鉴于我可能(或可能没有)拥有的所有重定向,我如何获得返回内容的最新 URL?

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

编辑:HttpGet#getURI()返回原始呼叫地址

4

8 回答 8

64

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

  HttpGet#getURI();

编辑:你没有提到你是如何做重定向的。这对我们有用,因为我们自己处理 302。

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

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

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

于 2009-09-21T22:13:16.463 回答
42

在 HttpClient 4 中,如果您正在使用LaxRedirectStrategy或任何子类DefaultRedirectStrategy,这是推荐的方式(参见源代码DefaultRedirectStrategy):

HttpContext context = new BasicHttpContext();
HttpResult<T> result = client.execute(request, handler, context);
URI finalUrl = request.getURI();
RedirectLocations locations = (RedirectLocations) context.getAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS);
if (locations != null) {
    finalUrl = locations.getAll().get(locations.getAll().size() - 1);
}

从 HttpClient 4.3.x 开始,上面的代码可以简化为:

HttpClientContext context = HttpClientContext.create();
HttpResult<T> result = client.execute(request, handler, context);
URI finalUrl = request.getURI();
List<URI> locations = context.getRedirectLocations();
if (locations != null) {
    finalUrl = locations.get(locations.size() - 1);
}
于 2013-12-11T00:37:39.440 回答
14
    HttpGet httpGet = new HttpHead("<put your URL here>");
    HttpClient httpClient = HttpClients.createDefault();
    HttpClientContext context = HttpClientContext.create();
    httpClient.execute(httpGet, context);
    List<URI> redirectURIs = context.getRedirectLocations();
    if (redirectURIs != null && !redirectURIs.isEmpty()) {
        for (URI redirectURI : redirectURIs) {
            System.out.println("Redirect URI: " + redirectURI);
        }
        URI finalURI = redirectURIs.get(redirectURIs.size() - 1);
    }
于 2014-05-03T13:52:37.760 回答
7

我在HttpComponents 客户端文档中找到了这个

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
HttpGet httpget = new HttpGet("http://localhost:8080/");
CloseableHttpResponse response = httpclient.execute(httpget, context);
try {
    HttpHost target = context.getTargetHost();
    List<URI> redirectLocations = context.getRedirectLocations();
    URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
    System.out.println("Final HTTP location: " + location.toASCIIString());
    // Expected to be an absolute URI
} finally {
    response.close();
}
于 2016-01-23T07:55:26.373 回答
6

恕我直言,基于 ZZ Coder 解决方案的改进方法是使用 ResponseInterceptor 来简单地跟踪最后一个重定向位置。这样您就不会丢失信息,例如在标签之后。如果没有响应拦截器,您将丢失主题标签。示例:http: //j.mp/OxbI23

private static HttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllTrustManager() };
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));
    schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));

    HttpParams params = new BasicHttpParams();
    ClientConnectionManager cm = new org.apache.http.impl.conn.SingleClientConnManager(schemeRegistry);

    // some pages require a user agent
    AbstractHttpClient httpClient = new DefaultHttpClient(cm, params);
    HttpProtocolParams.setUserAgent(httpClient.getParams(), "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:13.0) Gecko/20100101 Firefox/13.0.1");

    httpClient.setRedirectStrategy(new RedirectStrategy());

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            if (response.containsHeader("Location")) {
                Header[] locations = response.getHeaders("Location");
                if (locations.length > 0)
                    context.setAttribute(LAST_REDIRECT_URL, locations[0].getValue());
            }
        }
    });

    return httpClient;
}

private String getUrlAfterRedirects(HttpContext context) {
    String lastRedirectUrl = (String) context.getAttribute(LAST_REDIRECT_URL);
    if (lastRedirectUrl != null)
        return lastRedirectUrl;
    else {
        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());
        return currentUrl;
    }
}

public static final String LAST_REDIRECT_URL = "last_redirect_url";

就像 ZZ Coder 的解决方案一样使用它:

HttpResponse response = httpClient.execute(httpGet, context);
String url = getUrlAfterRedirects(context);
于 2012-07-25T16:06:58.563 回答
4

我认为找到最后一个 URL 的更简单方法是使用 DefaultRedirectHandler。

package ru.test.test;

import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.impl.client.DefaultRedirectHandler;
import org.apache.http.protocol.HttpContext;

public class MyRedirectHandler extends DefaultRedirectHandler {

    public URI lastRedirectedUri;

    @Override
    public boolean isRedirectRequested(HttpResponse response, HttpContext context) {

        return super.isRedirectRequested(response, context);
    }

    @Override
    public URI getLocationURI(HttpResponse response, HttpContext context)
            throws ProtocolException {

        lastRedirectedUri = super.getLocationURI(response, context);

        return lastRedirectedUri;
    }

}

使用此处理程序的代码:

  DefaultHttpClient httpclient = new DefaultHttpClient();
  MyRedirectHandler handler = new MyRedirectHandler();
  httpclient.setRedirectHandler(handler);

  HttpGet get = new HttpGet(url);

  HttpResponse response = httpclient.execute(get);

  HttpEntity entity = response.getEntity();
  lastUrl = url;
  if(handler.lastRedirectedUri != null){
      lastUrl = handler.lastRedirectedUri.toString();
  }
于 2012-04-23T18:18:35.267 回答
2

在 2.3 版本中,Android 仍然不支持以下重定向(HTTP 代码 302)。我刚刚阅读了位置标题并再次下载:

if (statusCode != HttpStatus.SC_OK) {
    Header[] headers = response.getHeaders("Location");

    if (headers != null && headers.length != 0) {
        String newUrl = headers[headers.length - 1].getValue();
        // call again the same downloading method with new URL
        return downloadBitmap(newUrl);
    } else {
        return null;
    }
}

这里没有循环重定向保护,所以要小心。更多关于博客的信息 使用 AndroidHttpClient 进行 302 重定向

于 2011-01-27T18:08:24.487 回答
0

这就是我设法获取重定向 URL 的方式:

Header[] arr = httpResponse.getHeaders("Location");
for (Header head : arr){
    String whatever = arr.getValue();
}

或者,如果您确定只有一个重定向位置,请执行以下操作:

httpResponse.getFirstHeader("Location").getValue();
于 2013-07-02T13:23:51.770 回答