使用dto对象数组构建HttpMethod POST请求

问题描述 投票:0回答:1

我需要将对象数组作为请求正文发送到POST API,如下所示。

[{
 "k1": "v1",
 "k2": "v2",
 "k3": 1
  }]

我的dto文件如下所示

public class Request {

    @JsonProperty("k1")
    private String k1;

    @JsonProperty("k2")
    private String k2;

    @JsonProperty("k3")
    private int k3;

    //setters and getters

    //override toString
    public String toString() {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        return gson.toJson(this);
    }

}

我的客户端实现如下所示

final HttpEntity<Request> httpEntity = new HttpEntity<Request>(requestBody, headers);

final ResponseEntity<String> responseEntity = restTemplate.exchange(URI, HttpMethod.POST, httpEntity, String.class);

现在我需要帮助来构建requestBody

作为JS开发人员,我对Java相当陌生。所以,请客气。谢谢。

java spring-boot rest post http-method
1个回答
0
投票

提到的JSON

[{
 "k1": "v1",
 "k2": "v2",
 "k3": 1
  }]

Request对象的列表。因此,此requestBody对象必须类似于-

List<Request> requestBody = //your logic to build this variable;

httpEntity中的更改以接受此请求正文:

final HttpEntity<List<Request>> httpEntity = new HttpEntity<List<Request>>(requestBody, headers);

更新:构建requestBody变量的示例:

Request request1 = new Request("v1", "v2", 1);

List<Request> requestBody = new ArrayList<>();
requestBody.add(request1);
© www.soinside.com 2019 - 2024. All rights reserved.