Search code examples
javaspring-bootmicroservicesresttemplate

How to consume service Using Resttemplate.exchange


I want to make a service call using Resttemplate.exchange method: See the below is my service to which i want to consume:

@PostMapping(value = "/service", consumes = { "application/x-www-form-urlencoded" })
    public ServiceObligationResponse retrieveServiceObligationResponsesByServiceObligationRequests(
            @Valid @RequestParam Map<String, String> params,
            @RequestHeader(value = KEY, required = true) String key,
            @RequestHeader(value = ID, required = true) String id,
            @RequestHeader(value = AUTH_HEADER, required = true) String authHeader)
            throws CustomUnAuthorizedException {
 Some code ............... 
}

Please help i am new to microservice


Solution

  • Just add headers and params to RestTemplate object.

    final String uri = "http://localhost:8080/service";
    
    RestTemplate restTemplate = new RestTemplate();
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.set("KEY", "myKey");
    headers.set("ID", "myId");
    headers.set("AUTH_HEADER", "myAuthHeader");
    
    Map<String, String> params = new HashMap<>();
    params.put("param1", "value1");
    
    HttpEntity<Map<String, String>> request = new HttpEntity<>(params , headers);
    
    ResponseEntity<MyResponse> response = restTemplate.exchange(uri, HttpMethod.POST, request, MyResponse.class);
    
    if(response.getStatusCode() == HttpStatus.OK) {
      MyResponse resObj = response.getBody();
      // do something with the response
    }