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) }
String url = "http://test.com/Services/rest/{id}/Identifier"; Map<String, String> params = new HashMap<String, String>(); params. put("id", "1234"); UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder. fromUriString(url); uriComponentsBuilder. uriVariables(params); Uri uri = uriComponentsBuilder.
Class RestTemplateBuilder. Builder that can be used to configure and create a RestTemplate . Provides convenience methods to register converters , error handlers and UriTemplateHandlers .
I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders . (You can also specify the HTTP method you want to use.) For example, RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.
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);
If you are using Spring Boot, you can use org.springframework.boot.web.client.RestTemplateBuilder.rootUri(baseUrl).build()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With