28

Is there any other way to initialize RestTemplate with base URI other than extending RestTemplate and overriding the execute method.currently i have the code like below.Thanks

class CustomRestTemplate extends RestTemplate {
String baseUrl

@Override
protected  T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor responseExtractor) throws RestClientException {
    return super.doExecute(new URI(baseUrl + url.toString()), method, requestCallback, responseExtractor)
}
Amit Swain
  • 301
  • 1
  • 6
  • 11

5 Answers5

51

Spring 5.0:

This sends a GET request to http://localhost:8080/myservice

RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory("http://localhost:8080"));
restTemplate.getForObject("/myservice", String.class);
Mateusz Stefek
  • 3,478
  • 2
  • 23
  • 28
28

If you are using Spring Boot, you can use org.springframework.boot.web.client.RestTemplateBuilder.rootUri(baseUrl).build()

Somu
  • 3,593
  • 6
  • 34
  • 44
11

You can create your custom DefaultUriTemplateHandler

DefaultUriTemplateHandler defaultUriTemplateHandler = new DefaultUriTemplateHandler();
defaultUriTemplateHandler.setBaseUrl(url);

And then add it to restTemplate

return new RestTemplateBuilder()
      .uriTemplateHandler(defaultUriTemplateHandler)
      .build();
dehasi
  • 2,644
  • 1
  • 19
  • 31
  • 3
    DefaultUriTemplateHandler has been Deprecated as of 5.0 in favor of DefaultUriBuilderFactory. So we should avoid using it. – Arvind Kumar Jul 31 '19 at 09:52
0

Spring's RestTemplate (version 4.2.0.RELEASE) support a method named setUriTemplateHandler. If this is never set, it contains a DefaultUriTemplateHandler

DefaultUriTemplateHandler supports a method named 'setBaseUrl`

So, you can set the base URL there.

Darius X.
  • 2,886
  • 4
  • 24
  • 51
-7

AFAIK there is no way other than what you have listed above

Farooq Khan
  • 570
  • 4
  • 11