[英]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.我已经为请求创建了模型,header 和具有相应字段的有效负载。
How do I send this using rest template?如何使用 rest 模板发送这个?
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. 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.创建一个新的 HttpEntity,用 headers 和 body 填充它,然后使用像这样的 RestTemplate 进行交换。 Payload - is a class containing your payload, and I assumed you have a builder (you can use just a map, indeed)
有效载荷 - 是一个包含有效载荷的 class,我假设您有一个构建器(实际上,您可以只使用 map)
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.