RestTemplate Exchange Get Example

By | | Updated : 2021-10-16 | Viewed : 46 times

RestTemplate Exchange Get Example

We already explored of spring boot getForEntity()/getForObject() to invoke get API and postForEntity()/postForObject() to invoke post API. But we need in some cases only one method for all types of APIs. So we can use exchange().

RestTemplate Exchange Method

Different types of exchange methods are available in RestTemplate to consume different types of API located in other microservice.

Different types of exchange() methods in RestTemplate
ResponseEntity<T>	exchange(RequestEntity<?> entity, Class<T> responseType)

ResponseEntity<T>	exchange(RequestEntity<?> entity, ParameterizedTypeReference<T> responseType)

ResponseEntity<T>	exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String,?> uriVariables)

ResponseEntity<T>	exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)

ResponseEntity<T>	exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Map<String,?> uriVariables)

ResponseEntity<T>	exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables)

ResponseEntity<T>	exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType)

ResponseEntity<T>	exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)

RestTemplate Exchange Get Example

With Query Parameters And Headers ( RequestEntity )

Here we are consuming the get API by exchange() method. In this exchange() we are passing the RequestEntity object. Please see the below given example.

restTemplate Client: exchange() with With Query Parameters And Headers

    //get:Using RequestEntity with Params and Headers
    public CustomerDetails getCustomerDetExchangeRequestEntity1(Long id, String firstName) throws URISyntaxException {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("firstName", firstName);
        URI uri = UriComponentsBuilder.newInstance().scheme("http").host("localhost").port(8082)
                .path("restTemplateServer/api/customerDetails/{id}/{firstName}").buildAndExpand(map).toUri();
        RequestEntity requestEntity = new RequestEntity(headers, HttpMethod.GET, uri);
        return restTemplate.exchange(requestEntity, CustomerDetails.class).getBody();
    }
restTemplate Server: exchange() with With Query Parameters And Headers
    @GetMapping("/customerDetails/{id}/{firstName}")
    public ResponseEntity<?> getCustomerDetailsByIdAndFirstName(@PathVariable Long id,@PathVariable String firstName) throws ExecutionException, InterruptedException {
        CustomerDetails customerDetails = customerDetailsServiceImpl.findByIdAndByFirstName(id,firstName);
        return ResponseEntity.ok(customerDetails);
    }

Note: Here we can use RequestEntity without headers also.

With Query Parameters And Headers ( HttpEntity )

Here we are using the same exchange() method but here we can pass the URI variables. URI variables will be used to fill the values for the path variable. Please notice below the given code snippet.

restTemplate Client: exchange() with With Query Parameters And Headers
    //get:Using HttpEntity with Params, Headers
    public CustomerDetails getCustDetailsExchangeHttpEntity1(Long id, String firstName) {
        String url = "http://localhost:8082/restTemplateServer/api/customerDetails/{id}/{firstName}";
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("firstName", firstName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<>(headers);
        return restTemplate.exchange(url, HttpMethod.GET, entity, CustomerDetails.class, map).getBody();
    }
restTemplate Server: exchange() with With Query Parameters And Headers
@GetMapping("/customerDetails/{id}/{firstName}")
    public ResponseEntity<?> getCustomerDetailsByIdAndFirstName(@PathVariable Long id,@PathVariable String firstName) throws ExecutionException, InterruptedException {
        CustomerDetails customerDetails = customerDetailsServiceImpl.findByIdAndByFirstName(id,firstName);
        return ResponseEntity.ok(customerDetails);
    }

So here in the URL, the path variable has existed. So we need to send the values for the same through the exchange() method. Notice we pass Map in exchange() for the same URI Vars which are the values for path variables in the URL.

With Query Parameters And Headers And ParameterizedTypeReference ( HttpEntity )

RequestEntity and ResponseEntity represent both request and response in HTTP Method execution. So to make these entities generic then we can use ParameterizedTypeReference. Please notice the given example.

restTemplate Client: exchange() With Query Parameters And Headers And ParameterizedTypeReference ( HttpEntity )
    //get:Using HttpEntity with Params, Headers and With ParameterizedTypeReference
    public CustomerDetails getCustomerDetailsExchangeHttpEntity2(Long id, String firstName) {
        String url = "http://localhost:8082/restTemplateServer/api/customerDetails/{id}/{firstName}";
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("firstName", firstName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ParameterizedTypeReference<CustomerDetails> typeRef = new ParameterizedTypeReference<>() {};
        return restTemplate.exchange(url, HttpMethod.GET, entity, typeRef, map).getBody();
    }

Here is the repo SpringBoot-RestTemplate-Example-Appfor the entire example.

Leave A Reply