Spring: how to get rootUri from RestTempalte

Viewed 4630

I'm using this configuration class to initialize RestTemplate:

@Configuration
public class RestTemplateConfig {

  @Value("${endpoint-url}")
  private String endpointUrl;

  @Bean
  public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder
        .rootUri(endpointUrl)
        .messageConverters(new MappingJackson2HttpMessageConverter())
        .build();
  }
}

And in one of my service's method I use the code:

RootUriTemplateHandler handler = (RootUriTemplateHandler) restTemplate.getUriTemplateHandler();
String uri = handler.getRootUri();
restTemplate.postForLocation(uri, request);

To get this URI. Is there an easier method to get this rootUri (without casting)? Or to execute the post request directly to rootUri?

3 Answers
restTemplate.getUriTemplateHandler().expand("/")

You can execute the post request directly to rootUri, as long as the uri you provide to the restTemplate.postForLocation starts with "/". In that case, Spring will automatically add the baseURI provided in the restTemplate constructor.

@Configuration
public class RestTemplateConfig {

   @Bean
   public RestTemplate restTemplate(RestTemplateBuilder builder,
                                    @Value("${endpoint-url}") String endpointUrl) {
     return builder
       .rootUri(endpointUrl)
       .messageConverters(new MappingJackson2HttpMessageConverter())
       .build();
   }
}

In your service's method:

// Make a POST call to ${endpoint-url}/foobar

String uri = "/foobar"; // The leading "/" is important!
restTemplate.postForLocation(uri, request);
Related