java – 如何使用Spring RestTemplate在POST中传递数组?

weixin_38064085 2019-09-12 11:35:14
我使用Spring的RestTemplate在POST中传递数组时遇到了困难.以下是我使用的代码: 我在这里调用RestTemplate: private static void sendEntries() { RestTemplate restTemplate = new RestTemplate(); String uri = "http://localhost:8080/api/log/list.json"; // Both LogEntry and ExceptionEntry extend Entry LogEntry entry1 = new LogEntry(); ExceptionException entry2 = new ExceptionEntry(); Entry[] entries = {entry1, entry2}; entries = restTemplate.postForObject(uri, entries, Entry[].class); System.out.println(new Gson().toJson(entries)); } 控制器包含: @RequestMapping(value = "api/log/list", method = RequestMethod.POST) public @ResponseBody Entry[] saveList(@RequestBody Entry[] entries) { for (Entry entry : entries) { entry = save(entry); } return entries; } 这导致: org.springframework.web.client.HttpClientErrorException: 400 Bad Request 它看起来不像是将数组添加到请求中.当我不尝试传递数组时,所有其他POST请求都有效.我只是不确定我需要做什么才能使数组正确传递. 这是正确的做法吗?是否可以通过集合?
...全文
1294 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38080439 2019-09-12
  • 打赏
  • 举报
回复
你可以查看这篇文章:How to pass List or String array to getForObject with Spring RestTemplate,该帖子的解决方案是: 列表或其他类型的对象可以使用RestTemplate的postForObject方法发布.我的解决方案如下: 控制器: @RequestMapping(value="/getLocationInformations", method=RequestMethod.POST) @ResponseBody public LocationInfoObject getLocationInformations(@RequestBody RequestObject requestObject) { // code block } 创建一个发布到服务的请求对象: public class RequestObject implements Serializable { public List<Point> pointList = null; } public class Point { public Float latitude = null; public Float longitude = null; } 创建响应对象以从服务获取值: public class ResponseObject implements Serializable { public Boolean success = false; public Integer statusCode = null; public String status = null; public LocationInfoObject locationInfo = null; } 使用请求对象发布点列表并从服务获取响应对象: String apiUrl = "http://api.website.com/service/getLocationInformations"; RequestObject requestObject = new RequestObject(); // create pointList and add to requestObject requestObject.setPointList(pointList); RestTemplate restTemplate = new RestTemplate(); ResponseObject response = restTemplate.postForObject(apiUrl, requestObject, ResponseObject.class); // response.getSuccess(), response.getStatusCode(), response.getStatus(), response.getLocationInfo() can be used

435

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧