pixel pixel - 4 months ago 41
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?

Answer
  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
        .create()
        .setRedirectStrategy( new DefaultRedirectStrategy() {

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

                System.out.println(response);

                // 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;
            }
        })
        .build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
.......