HttpClient 4 - how to capture last redirect URL HttpClient 4 - how to capture last redirect URL java java

HttpClient 4 - how to capture last redirect URL


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

  HttpGet#getURI();

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

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.


In HttpClient 4, if you are using LaxRedirectStrategy or any subclass of DefaultRedirectStrategy, this is the recommended way (see source code of 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);}

Since HttpClient 4.3.x, the above code can be simplified as:

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


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