gpt4 book ai didi

java - 如何在 POST 方法(RestTemplate)中将 List 作为正文传递

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:43 25 4
gpt4 key购买 nike

我正在尝试使用restTemplate发出Post请求,问题是API正在接受List<Users>在正文中作为 POST 请求

public class Users {

String id;

String name;

String gender;

}

我已将元素添加为

List<Users> userList=new ArrayList<Users>();
userList.add(new Users("1","AA","Male"));
userList.add(new Users("2","BB","Male"));
userList.add(new Users("3","CC","Female"));

AS

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);

ResponseEntity<String> response = restTemplate.postForEntity(URL.toString(), HttpMethod.POST, entity, String.class);

这里我应该如何将我的 userList 传递到请求正文中?

最佳答案

您需要在 HttpEntity 中传递数据。您可以使用来自 jackson-databind lib 的 ObjectMapper 将列表转换为 json。

String userJsonList = objectMapper.writeValueAsString(userList);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(userJsonList, headers);

ResponseEntity<String> response = restTemplate.postForEntity(URL.toString(), HttpMethod.POST, entity, String.class);

所以基本上它会将数据作为 json 字符串传递。

关于java - 如何在 POST 方法(RestTemplate)中将 List<Objects> 作为正文传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50035890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com