Search code examples
springresttemplate

How can I disable Spring RestTemplate following a HTTP redirect response?


I'm integrating with an ancient service that is adds jsessionid to the URL and redirects to it. I'm using RestTemplate to talk to the service.

The problem is that it follows the redirect forever, since I'm not setting the jsession cookie.

How do I turn off following the redirects in Spring RestTemplate?


Solution

  • I figured out one way to do it, don't know if this is the preferred way to do it.

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        final HttpComponentsClientHttpRequestFactory factory = 
                 new HttpComponentsClientHttpRequestFactory();
        CloseableHttpClient build = 
                 HttpClientBuilder.create().disableRedirectHandling().build();
        factory.setHttpClient(build);
        restTemplate.setRequestFactory(factory);
        return restTemplate;
    }