How to add base URI in RestTemplate

Amit Swain picture Amit Swain · Jun 21, 2017 · Viewed 17.7k times · Source

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

Answer

Mateusz Stefek picture Mateusz Stefek · Jan 4, 2018

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