Search code examples
javaspring-bootrequestresttemplatepojo

How to I send a Rest Template Request Body with multiple objects in it


I have to send a request body like this

{
    "request": {
        "header": {
            "correlationId": "Test",
            "appId": "12345"
        },
        "payload": {
            "leadId": "12345",
            "applicationNo": "",
            "proposalNo": "P123",
            "policyNo": "100",
            "issuanceDt": "01-06-2022",
            "docName": "ABCD.pdf",
            "docType": "Proposal Form"
        }
    } 
}

I also have headers "username" and "password".

I have created Models for request, header and payload with respective fields.

How do I send this using rest template?


Solution

  • Create a new HttpEntity, populate it with headers and body and exchange, using RestTemplate like this. Payload - is a class containing your payload, and I assumed you have a builder (you can use just a map, indeed)

    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("correlationId", "value");
    httpHeaders.add("appId", "value");
    HttpEntity<Payload> httpEntity = new HttpEntity<>(Payload.builder()
    //bulider population goes here
    .build(),httpHeaders);
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.exchange(uri, HttpMethod.POST,httpEntity);