一.表单提交
Postman发送Get请求和Post请求
可以获取
//Get请求
@GetMapping("/form/get")
public void testFormGet(User user){}
@GetMapping("/form/get")
public void testFormGet(@RequestParam String name, @RequestParam String phone, @RequestParam Integer age){}
@GetMapping("/form/get")
public void testFormGet(String name, String phone, Integer age){}
@GetMapping("/form/get")
//不管发送过来的字段是什么类型,user都是Map<String, String>
public void testFormGet(@RequestParam Map user){
//Post请求
@PostMapping("/form/post")
public void testFormPost(User user){}
@PostMapping("/form/post")
public void testFormPost(@RequestParam String name, @RequestParam String phone, @RequestParam Integer age){}
@PostMapping("/form/post")
public void testFormPost(String name, String phone, Integer age){}
@PostMapping("/form/post")
public void testFormPost(@RequestParam Map user){}
不可以获取
//Get请求
@GetMapping("/form/get")
public void testFormGet(@RequestParam User user){}
@GetMapping("/form/get")
public void testFormGet(Map user){}
@GetMapping("/form/get")
public void testFormGet(TreeMap user){}
@GetMapping("/form/get")
public void testFormGet(@RequestParam TreeMap user){}
//Post请求
@PostMapping("/form/post")
public void testFormPost(@RequestParam User user){}
@PostMapping("/form/post")
public void testFormPost(Map user){}
@PostMapping("/form/post")
public void testFormPost(TreeMap user){}
@PostMapping("/form/post")
public void testFormPost(@RequestParam TreeMap user){}
程序发送Post和Get请求
Post请求,controller接收请求同上。
HttpHeaders httpHeaders = new HttpHeaders();
RestTemplate restTemplate = new RestTemplate();
String url = "http://127.0.0.1:8081/api/v1/form/post";
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
//两种方式都可以
//httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
params.add("name", "小明");
params.add("age", 18);
params.add("phone", "135********");
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(params, httpHeaders);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, POST, requestEntity, String.class);
System.out.println(responseEntity.getBody());
Post请求,controller接收请求同上。
RestTemplate restTemplate = new RestTemplate();
String url = "http://127.0.0.1:8081/api/v1/form/post";
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("name", "小明");
params.add("age", 18);
params.add("phone", "135********");
String result = restTemplate.postForObject(url, params, String.class);
System.out.println(result);
Get请求,controller接收请求同上。
RestTemplate restTemplate = new RestTemplate();
String url = "http://127.0.0.1:8081/api/v1/form/get?name={name}&age={age}&phone={phone}";
Map<String, String> map = new HashMap<>();
map.put("name","小明");
map.put("age","18");
map.put("phone", "135********");
//如果前端返回的map和实体类属性相同,可以转换为实体类对象
User responseEntity = restTemplate.getForObject(url,User.class,map);
System.out.println(responseEntity);