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發送接口能正確接收,應該是發送端格式問題
