mnd
mnd

Reputation: 2789

Set base URL/URI on Spring's RestTemplate in Spring 5.0

I'm using Spring 5's RestTemplate in a Spring Boot 2 app, and trying to set a base URL/URI on it, so that I don't have to prepend each request with it. This will also allow me to set this value based on a property.

Previous versions of ReleaseTemplate let you set the base url through the constructor (e.g. new ReleaseTemplate(baseUrl)). But this is no longer the case.

I see that the DefaultUriTemplateHandler class has a setBaseUrl() that it inherits from the AbstractUriTemplateHandler interface, but that class has since been deprecated. The suggested replacement class DefaultUriBuilderFactory does not have any such methods.

Any suggestions would be appreciated. Thanks.

Upvotes: 2

Views: 5828

Answers (1)

kakabali
kakabali

Reputation: 4033

Try using the following:-

String BASE_URI_TEMPLATE = "http://localhost:8080";

DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(BASE_URI_TEMPLATE);

RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(uriBuilderFactory);
restTemplate.getForObject("/test", String.class); // like you may have used earlier

Upvotes: 5

Related Questions