Spring RestTemplate : Follow Redirect Automatically

Follow Redirect Automatically in Spring RestTemplate....

Now since the boost of micro-service based architecture we use web-services a lot. Spring boot is one of the popular framework to work on Micro-service based architecture. Soap web-services are legacy swords and REST(Representational State transfer) is now the modern time weapon in everybody's arsenal.

When we use REST with Spring we have lot of inbuilt functionalities (Converting Response and request to Domain objects, Error handling, HttpStatus code and many more...) offered by Spring.

Today we are going to check about RestTemplate.

Spring's central class for synchronous client-side HTTP access. This is what Spring says about RestTemplate.
RestTemplate provides support to all HTTP Methods. Most popular are GET and POST.

So when we are calling any webservice endpoint using RestTemplate GET or POST there are chances that in response you get Redirect response (302 HTTP Status code). Which indicates that this response is going yo redirect to some other URL. RestTemplate doesnt handle such redirect automatically. So, To follow the redirect to location header URL in 302 response in case of :
  • GET: 
In case of GET Spring RestTemplate follow the redirect command automatically. The reason behind is it internally uses
SimpleClientHttpRequestFactory. This class already set the redirection true for GET method check.
RestTemplate restTemplate = new RestTemplate();
ResponseEntitymybean<MyBean>response = restTemplate.getForEntity("webservice endPoint url", MyBean.class);

  • POST: 

  • To follow the redirection in case of RestTemplate POST method call, We have to use a different request factory, like HttpComponentsClientHttpRequestFactory, and set it to use an HttpClient with the required settings to follow the redirect as below:
    final RestTemplate restTemplate = new RestTemplate();
    final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    final HttpClient httpClient = HttpClientBuilder.create()
                                                   .setRedirectStrategy(new LaxRedirectStrategy())
    Map<String, String> params = new HashMap<String, String>();
    params.put("email", "yourname@gmail.com");
    ResponseEntity response = restTemplate.postForEntity(""webservice endPoint url"", params, String.class);

    The LaxRedirectStrategy allows us to redirect in case of HEAD, GET, POST, DELETE.