I am using RestTemplate
to make an Http call to one of my service and I would like to have timeout for my Http Request -
public static String getResponse(final String url) {
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
String response = restTemplate.getForObject(url, String.class);
// return response
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(2000);
factory.setConnectTimeout(2000);
return factory;
}
So I came up with the above code after reading this How to Set HTTP Request Timeouts With Spring RestTemplate.
Is this the efficient way of using RestTemplate
along with ClientHttpRequestFactory
? Since with this for each call, it will make a new RestTemplate
object. Earlier, I was not using any timeout for RestTemplate
so I declared RestTemplate
as static final and below was my code -
private static final RestTemplate restTemplate = new RestTemplate();
public static String getResponse(final String url) {
String response = restTemplate.getForObject(url, String.class);
// return response
}
I am not sure what is the right way of using RestTemplate
along with ClientHttpRequestFactory
. Should they both be declared as static? I am opting for code review to see whether there is any improvement I can do here?