Home > Software design >  How to I send a Rest Template Request Body with multiple objects in it
How to I send a Rest Template Request Body with multiple objects in it

Time:07-25

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?

CodePudding user response:

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);

CodePudding user response:

For Header, you just need to add parameters in the headers of HTTP request, Payload is what you are looking for, You can define a DTO class having the same JSON structure which will then be automatically deserialized and mapped to your DTO class.

public class Payload{
public String leadId;
public String applicationNo;
public String proposalNo;
public String policyNo;
public String issuanceDt;
public String docName;
public String docType;

}

  • Related