Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 921
pixel Avatar asked Oct 16 '25 19:10

pixel


2 Answers

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();
like image 87
znaya Avatar answered Oct 18 '25 08:10

znaya


  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);
.......
like image 35
Michal Foksa Avatar answered Oct 18 '25 07:10

Michal Foksa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!