pixel pixel - 7 months ago 80
Java Question

How to get redirected url from RestTemplate?

I would like to call RestTemplate with http GET and retrieve status code and redirected url (if there was one).

How to achieve that?

  1. Create Apache HttpClient with custom RedirectStrategy where you can intercept intermediate response(s) when redirect occurred.
  2. Replace default request factory with HttpComponentsClientHttpRequestFactory and new Apache HttpClient.

Have a look at org.apache.http.client.RedirectStrategy for more information. Or reuse DefaultRedirectStrategy as in the following example:

CloseableHttpClient httpClient = HttpClientBuilder
        .setRedirectStrategy( new DefaultRedirectStrategy() {

            public boolean isRedirected(HttpRequest request, HttpResponse response,
                    HttpContext context) throws ProtocolException {


                // If redirect intercept intermediate response.
                if (super.isRedirected(request, response, context)){
                    int statusCode  = response.getStatusLine().getStatusCode();
                    String redirectURL = response.getFirstHeader("Location").getValue();
                    System.out.println("redirectURL: " + redirectURL);
                    return true;
                return false;
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);