Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add base URI in RestTemplate

Tags:

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) } 
like image 215
Amit Swain Avatar asked Jun 21 '17 19:06

Amit Swain


People also ask

How do you pass URL parameters in RestTemplate?

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.

What is the use of RestTemplateBuilder?

Class RestTemplateBuilder. Builder that can be used to configure and create a RestTemplate . Provides convenience methods to register converters , error handlers and UriTemplateHandlers .

How do you set a RestTemplate header?

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.


2 Answers

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); 
like image 193
Mateusz Stefek Avatar answered Sep 17 '22 15:09

Mateusz Stefek


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

like image 23
Somu Avatar answered Sep 18 '22 15:09

Somu