API接口1:添加一条记录
@PostMapping(path="/addUser") //用请求参数 @ResponseBody //必须加@RequestBody才能接收到postForObject发来的数据 public int addUser(@RequestBody User user) { try { userCrudReposity.save(user); return 0; } catch(Exception e){ return -1; } }
调用代码
RestTemplate restTemplate = new RestTemplate();
User user=new User("王","宏伟","email");
int ret = restTemplate.postForObject("http://localhost:8888/demo/addUser",user,int.class); //int.class是http://localhost:8888/demo/addUser返回的类型
return ret;
API接口2:添加多条记录
@PostMapping(path="/addUsers") //用请求参数 @ResponseBody //必须加@RequestBody才能接收到postForObject发来的数据 public int addUsers(@RequestBody List<User> list) { try { userCrudReposity.saveAll(list); return 0; } catch(Exception e){ return -1; } }
调用代码:
List<User> list=new ArrayList<User>();
RestTemplate restTemplate = new RestTemplate();
User user1=new User("王","宏伟1","email");
User user2=new User("王","宏伟2","email");
list.add(user1);
list.add(user2);
int ret = restTemplate.postForObject("http://localhost:8888/demo/addUsers",list,int.class);
API接口3:JSON字符串,添加多条记录
@PostMapping(path="/addUsers_JSON") //用请求参数 @ResponseBody //必须加@RequestBody才能接收到postForObject发来的数据 public int addUsers_JSON(@RequestBody String jsonStr) { try { jsonStr = URLDecoder.decode(jsonStr,"utf-8"); List<User> users= JSONArray.parseArray(jsonStr,User.class); userCrudReposity.saveAll(users); return 0; } catch(Exception e){ return -1; } }
调用代码
List<User> list=new ArrayList<User>(); RestTemplate restTemplate = new RestTemplate(); User user1=new User("王","宏伟a","email"); User user2=new User("王","宏伟b","email"); list.add(user1); list.add(user2); String jsonString=JSON.toJSONString(list); String str = URLEncoder.encode(jsonString, "utf-8"); //字符串中中文,必须编码,否则接收错误 int ret = restTemplate.postForObject("http://localhost:8888/demo/addUsers_JSON",str,int.class);
说明:语句 restTemplate.postForObject("http://localhost:8888/demo/addUsers_JSON",str,int.class);中的中文字符串必须编码,否则接收到后中文错误。
另外一种调用方式
@GetMapping("/addUsers_JSON2") public int addUsers_JSON2() { List<User> list=new ArrayList<User>(); RestTemplate restTemplate = new RestTemplate(); User user1=new User("王","宏伟 addUsers_JSON1","email"); User user2=new User("王","宏伟 addUsers_JSON1","email"); list.add(user1); list.add(user2); String jsonString=JSON.toJSONString(list); HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); HttpEntity<String> formEntity = new HttpEntity<String>(jsonString, headers); int result = restTemplate.postForObject("http://localhost:8888/demo/addUsers_JSON1", formEntity, int.class); // 这里没有编码,接口不需要解码 return result; }
原因见:https://www.cnblogs.com/zique/p/6171862.html , 用Postman发送接口能正确接收,应该是发送端格式问题