繁体   English   中英

如何发送包含多个对象的 Rest 模板请求正文

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

我必须发送这样的请求正文

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

我也有标题“用户名”和“密码”。

我已经为请求创建了模型,header 和具有相应字段的有效负载。

如何使用 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.

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

}

创建一个新的 HttpEntity,用 headers 和 body 填充它,然后使用像这样的 RestTemplate 进行交换。 有效载荷 - 是一个包含有效载荷的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM