Search code examples
springrest

Spring RestTemplate POST Query with Headers and Body


I need to consume the given API definition, But I am not able to find a function call that takes both headers and request body at documentation. Please suggest which function of RestTemplate to use here.

@RequestMapping(value = "/createObject", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON_VALUE, 
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CreateObjectOutput> createObject(
        @RequestBody CreateObjectInput req) 
{
    CreateObjectOutput out = new CreateObjectOutput();
    ///// Some Code
    return new ResponseEntity<CreateObjectOutput>(out, HttpStatus.OK);
}

Solution

  • RestTemplate template = new RestTemplate();
    CreateObjectInput payload = new CreateObjectInput();
    
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    
    HttpEntity<CreateObjectOutput> requestEntity = 
         new HttpEntity<>(payload, headers);
    CreateObjectOutput response = 
       template.exchange("url", HttpMethod.POST, requestEntity, 
                  CreateObjectOutput.class);