pixel
pixel

Reputation: 26441

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?

Upvotes: 4

Views: 16481

Answers (3)

znaya
znaya

Reputation: 331

Using Spring and overriding prepareConnection() in SimpleClientHttpRequestFactory...

RestTemplate restTemplate = new RestTemplate( new SimpleClientHttpRequestFactory(){
    @Override
    protected void prepareConnection( HttpURLConnection connection, String httpMethod ) {
        connection.setInstanceFollowRedirects(false);
    }
} );

ResponseEntity<Object> response = restTemplate.exchange( "url", HttpMethod.GET, null, Object.class );
int statusCode = response.getStatusCodeValue();
String location = response.getHeaders().getLocation() == null ? "" : response.getHeaders().getLocation().toString();

Upvotes: 5

Mateusz Stefek
Mateusz Stefek

Reputation: 3846

var responseEntity = restTemplate.exchange("someurl", HttpMethod.GET, null, Object.class);
HttpHeaders headers = responseEntity.getHeaders();
URI location = headers.getLocation();
location.toString();

Upvotes: 0

Michal Foksa
Michal Foksa

Reputation: 12024

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

Upvotes: 3

Related Questions