RestTemplate Exchange Post Example

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

RestTemplate Exchange Post Example

We have seen in the earlier tutorial about the rest template exchange get example. In this tutorial, we will learn about the same exchange method but it is for posting a resource to another post API.

RestTemplate Exchange Post Example

We will try to use different exchange methods for posting the resources to other post API. As you know exchange method is overloaded so we will try different options for posting resources to other post API.

With Parameters and Headers ( RequestEntity )

Let's code for posting resources through restTemplate's exchange methods. So here we are using RequestEntity as a parameter in the exchange method.

restTemplate Client: exchange() with With Query Parameters And Headers
//post:Using RequestEntity With Parameters and Headers
    public CustomerDetails createCustDetailsExchangeRequestEntity1(ProductDetails productDetails, Long id, String firstName) throws URISyntaxException {

        HttpHeaders headers = new HttpHeaders();
        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/product/{id}/{firstName}").buildAndExpand(map).toUri();
        RequestEntity requestEntity = new RequestEntity(productDetails, HttpMethod.POST, uri);
        return restTemplate.exchange(requestEntity, CustomerDetails.class).getBody();
    }
restTemplate Server: exchange() with With Query Parameters And Headers
@PostMapping(value = "/customerDetails/product/{id}/{firstName}")
    public ResponseEntity<?> createOrderAndUpdateCustomerDetails(@RequestBody ProductDetails productDetails,@PathVariable Long id,@PathVariable String firstName) {
        CustomerDetails resultedCustomerDetails = customerDetailsServiceImpl.createProductAndUpdateCustomerDetails(id,firstName, productDetails);
        return ResponseEntity.created(URI.create("/restTemplateServer/api/customerDetails/" + resultedCustomerDetails.getId())).body(resultedCustomerDetails);
    }

So here post data using the exchange method to other post API of another.

With Parameters, Headers, And With ParameterizedTypeRef ( RequestEntity )

Now we use the exchange() method with parameters like RequestEntity and ParameterizedTypeReference. Here is an example for exchange() method parameterized with RequestEntity and TypeRef.

restTemplate Client: exchange() with With Query Parameters, Headers and TypeRef
//post:Using RequestEntity With Parameters, Headers and With ParameterizedTypeReference
    public CustomerDetails createCustDetailsExchangeRequestEntity2(ProductDetails productDetails, Long id, String firstName) throws URISyntaxException {

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("firstName", firstName);
        ParameterizedTypeReference<CustomerDetails> typeRef = new ParameterizedTypeReference<>() {};
        URI uri = UriComponentsBuilder.newInstance().scheme("http").host("localhost").port(8082)
                .path("restTemplateServer/api/customerDetails/product/{id}/{firstName}").buildAndExpand(map).toUri();
        RequestEntity requestEntity = new RequestEntity(productDetails, HttpMethod.POST, uri);
        return restTemplate.exchange( requestEntity, typeRef).getBody();
    }
restTemplate Server: exchange() with With Query Parameters, Headers and TypeRef
@PostMapping(value = "/customerDetails/product/{id}/{firstName}")
    public ResponseEntity<?> createOrderAndUpdateCustomerDetails(@RequestBody ProductDetails productDetails,@PathVariable Long id,@PathVariable String firstName) {
        CustomerDetails resultedCustomerDetails = customerDetailsServiceImpl.createProductAndUpdateCustomerDetails(id,firstName, productDetails);
        return ResponseEntity.created(URI.create("/restTemplateServer/api/customerDetails/" + resultedCustomerDetails.getId())).body(resultedCustomerDetails);
    }

With Parameters and Headers ( HttpEntity )

As you know we can pass HttpEntity to exchange method. We will be looking into that part. So here is the example for the same.

restTemplate Client: exchange() with With Query Parameters And Headers
//post:Using HttpEntity Without Request Parameters and Headers
    public CustomerDetails createCustDetailsExchangeHttpEntity2(ProductDetails productDetails, Long id, String firstName) {
        String url = "http://localhost:8082/restTemplateServer/api/customerDetails/product/{id}/{firstName}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("firstName", firstName);
        HttpEntity<ProductDetails> httpEntity = new HttpEntity<>(productDetails,headers);
        return restTemplate.exchange(url, HttpMethod.POST, httpEntity, CustomerDetails.class,map).getBody();
    }
restTemplate Server: exchange() with With Query Parameters And Headers
@PostMapping(value = "/customerDetails/product/{id}/{firstName}")
    public ResponseEntity<?> createOrderAndUpdateCustomerDetails(@RequestBody ProductDetails productDetails,@PathVariable Long id,@PathVariable String firstName) {
        CustomerDetails resultedCustomerDetails = customerDetailsServiceImpl.createProductAndUpdateCustomerDetails(id,firstName, productDetails);
        return ResponseEntity.created(URI.create("/restTemplateServer/api/customerDetails/" + resultedCustomerDetails.getId())).body(resultedCustomerDetails);
    }

Please take look entire repo for this restTemplate-exchange-post-example

Leave A Reply