How can I disable spring resttemplate redirect when getting stuff?

Viewed 3796

I'm integrating with an ancient service that isrewriting the url with a jsessionid when I call it. I'm using resttemplate to talk with the service, and problem is that it is following the redirect forever, since I'm not setting the jsession cookie.

I'd like to turn off following redirects in spring resttemplate.

2 Answers

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; }

You can also write your own HttpRequestFactory class and override the default behaviour:

class CustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        super.prepareConnection(connection, httpMethod);
        connection.setInstanceFollowRedirects(false);
    }
}

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate httpClient(RestTemplateBuilder builder) {
        return builder
                .setConnectTimeout(Duration.ofSeconds(10))
                .setReadTimeout(Duration.ofSeconds(10))
                .requestFactory(CustomClientHttpRequestFactory.class)
                .build();
    }

}
Related