RestTemplate提交表单数据的三种方法之一

https://blog.csdn.net/yiifaa/article/details/77939282。此位仁兄得文章肯定是自己测试过之后写出来得。因为我遇到得问题。跟他描述得bug一毛一样。然后他得解决办法完全解决我得bug。感谢这个为兄弟!

Client:

@Test
public void getUsers() {
   List<UserEntity> response = restTemplate.exchange("http://localhost:8181/getUsers",
         HttpMethod.GET,
         null,
         new ParameterizedTypeReference<List<UserEntity>>() {}).getBody();
   for(UserEntity user : response){
      System.out.println("昵称:"+user.getNickName());
   }

}
SERVER:
@RequestMapping("/getUsers")
public List<UserEntity> getUsers() {
   List<UserEntity> users=userMapper.getAll();
   return users;
}

对于返回List<T>的请求采用上述的方式是OK的。上面的请求是无参请求。接下来有参请求:

Client:

@Test
public void pageUsers(){
   HttpHeaders headers = new HttpHeaders();
   //  请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
   headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
   //  封装参数,千万不要替换为Map与HashMap,否则参数无法传递
   MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
   params.add("userName", "zs");
   params.add("userSex", "WOMAN");
   params.add("currentPage", "1");
   params.add("pageSize", "3");
   HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
   Page<UserEntity> response = restTemplate.exchange("http://localhost:8181/getList",
         HttpMethod.POST, requestEntity,
         new ParameterizedTypeReference<Page<UserEntity>>() {}).getBody();
   
List<UserEntity> users = response.getContent();
System.out.println(users.size());
}

这里我遇到的问题就是请求的方式是表单请求还是Payload请求。因为这会直接影响到你服务端的参数接收代码:

 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

这种情况是表单提交。如果你用表单提交那么服务端参数接受就要用:

@RequestMapping(value = "/getList",method = RequestMethod.POST)
public Page<UserEntity> getList(@ModelAttribute UserParam userParam) {
    List<UserEntity> users=userMapper.getList(userParam);
    long count=userMapper.getCount(userParam);
    Page page = new Page(userParam,count,users);
    return page;
}

服务按代码接受入参不能用@RequestBody否则会报错误信息:

JSON parse error: Cannot deserialize instance of `java.lang.String` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_ARRAY token大概意思是你的请求入参不能封装为json字符串。

第二种请求方式是payload请求:  注意以下的代码没有经过本人的测试是抄上面仁兄的:

//  请求地址
String url = "http://localhost/mirana-ee/app/login";
RestTemplate client = new RestTemplate();
//  一定要设置header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//  将提交的数据转换为String
//  最好通过bean注入的方式获取ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Map<String, String> params= Maps.newHashMap();
params.put("username", "国米");
params.put("password", "123456");
String value = mapper.writeValueAsString(params);
HttpEntity<String> requestEntity = new HttpEntity<String>(value, headers);
//  执行HTTP请求
ResponseEntity<String> response = client.postForEntity(url, requestEntity , String.class );
System.out.println(response.getBody());

重点在这两行:

headers.setContentType(MediaType.APPLICATION_JSON_UTF8);指定请求的类型为JSON

String value = mapper.writeValueAsString(params);将参数转化为字符串

@RequestMapping(value="/login", consumes="application/json", method=RequestMethod.POST)
public Account getAccount(@RequestBody Account account) {
    account.setVersion(new Date());
    return account;
}





猜你喜欢

转载自blog.csdn.net/liyingying111111/article/details/80942926