Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading