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?
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;
}
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);
JSONObject header_payload_object=new JSONObject();
header_payload_object.put("payload",payload);//payload here is object of Payload Model
header_payload_object.put("header",header);//header here is object of Header Model
JSONObject request_object=new JSONObject();
request_object.put("request",header_payload_object);//final request json body
RestTemplate restTemplate=new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("username","dummyUsername");
headers.add("password","dummyPassword");// Assuming you are just adding username and password to headers seperately and not basic auth
HttpEntity<JSONObject> request = new HttpEntity<JSONObject>(request_object, headers);
ResponseEntity<String> response = restTemplate.exchange(url,HttpMethod.POST,request,String.class);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.