一. 以postForEntity为例
1. controller代码
/**
* 添加用户信息
* 请求参数支持表单数据
*
* 注意:针对ModelAttribute注解,后面只能够跟具体的类,不能是Map,
* 并且类必须有默认的构造器
*
* @param user
* @return
*/
@PostMapping("/form/user")
public int addUserByForm(@ModelAttribute User user){
logger.debug("user:"+user);
return 1;
}
2. RestTemplate代码
@Test
public void testPostForm(){
String url = HOST +"/api-demo/form/user";
//设置请求数据的格式
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//封装参数
MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
params.add("name", "song");
params.add("age", "12");
params.add("password", "song123");
//封装请求内容
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params,headers);
ResponseEntity<Integer> responseEntity = restTemplate.postForEntity(url,requestEntity,Integer.class);
logger.debug("responseEntity:"+responseEntity);
}