簡體   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