29

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

5 Answers 5

52

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);
28

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

1
  • looks like it does not work when you try to update the baseUrl String using Spring's @Value
    – jcflorezr
    May 10, 2021 at 19:26
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();
1
  • 3
    DefaultUriTemplateHandler has been Deprecated as of 5.0 in favor of DefaultUriBuilderFactory. So we should avoid using it. Jul 31, 2019 at 9: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.

-7

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.