我正在尝试使用RESTTEMPLATE提出发布请求,问题是API是在身体中接受List<Users>
作为邮政请求
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);
在这里我应该如何将我的用户列表传递到请求主体?
您需要在httpentity中传递数据。
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字符串。
对于发布请求,您可以使用" 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);
}