Application is using Spring rest template to call a webservice and i am using
restTemplate.exchage(url) to call the webservice.
Currently we are not passing any timeout value for this webservice call, How can i set a timeout value for Spring Rest template.
Asked
Active
Viewed 2.6k times
2

Sajal Saxena
- 191
- 1
- 3
- 16
-
http://springinpractice.com/2013/10/27/how-to-set-http-request-timeouts-with-spring-resttemplate/ – zapl Oct 07 '15 at 03:54
3 Answers
12
You can use code similar to following for setting connection timeout:
RestTemplate restTemplate = new RestTemplate();
((SimpleClientHttpRequestFactory)restTemplate.getRequestFactory()).setConnectTimeout(2000);
If your wish to set read timeout, you can have code similar to following:
((SimpleClientHttpRequestFactory)restTemplate.getRequestFactory()).setReadTimeout(2000);
The time is given in milliseconds here. For more info, you can visit the documentation page.

Balwinder Singh
- 2,272
- 5
- 23
- 34
5
RestTemplateBuilder introduced since Spring 1.4 could be used to set read and connect timeout settings for RestTemplate object. Here is sample code -
final RestTemplate restTemplate =
new RestTemplateBuilder()
.setConnectTimeout(Duration.ofMillis(connectTimeoutMillis))
.setReadTimeout(Duration.ofMillis(readTimeoutMillis))
.build();

realPK
- 2,630
- 29
- 22
-
1This is the right way! Other responses rely on modifying HttpClient, which can fail in runtime (i.e: implementation would not be available in your JVM). The downside: RestTemplateBuilder belongs to Spring Boot. – BeardOverflow Dec 09 '20 at 08:59
1
I use this approach based on these threads
int DEFAULT_TIMEOUT = 5000;
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(DEFAULT_TIMEOUT)
.setConnectionRequestTimeout(DEFAULT_TIMEOUT)
.setSocketTimeout(DEFAULT_TIMEOUT)
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
Spring RestTemplate Connection Timeout is not working
Java : HttpClient 4.1.2 : ConnectionTimeout, SocketTimeout values set are not effective