如何在POST方法中将List <objects>作为主体传递(RestTemplate)

时间:2018-04-26 06:07:27

标签: java spring list resttemplate

我正在尝试使用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传递给请求Body?

2 个答案:

答案 0 :(得分:0)

对于Post请求,您可以使用方法使用“method = RequestMethod.POST”或@POST注释。 对于列表对象,请检查以下代码。它会起作用。

public ResponseEntity<List<Users>> methodName(@QueryParam("id") String id){
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"));

return new ResponseEntity<List<Users>>(userList, HttpStatus.OK);
}

答案 1 :(得分:0)

您需要在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字符串传递。

相关问题