使用RestTemplate请求post json接口报错:Caused by: org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class com.xx.xxxbean] from JSON String; no single-String constructor/factory method (through reference chain: com.xxxx.xxxx["body"])
修改为使用map,而不是json字符串。
具体现象
刚开始请求时HttpEntity设置的参数为json字符串,HttpEntity<String> request = new HttpEntity<>(jsonParam, headers);
请求时报如上错误
Map<String, String> param = new HashMap();
param.put("userName", "tom");
param.put("password", encrypt);
String jsonParam = JSON.toJSONString(param);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
HttpEntity<String> request = new HttpEntity<>(jsonParam, headers);
ResponseEntity<String> stringResponseEntity = null;
try {
stringResponseEntity = restTemplate.postForEntity("http://localhost:8009/xxx/userLoginAuth", request, String.class);
HttpStatus statusCode = stringResponseEntity.getStatusCode();
logger.info("===:{}", statusCode);
} catch (RestClientException e) {
logger.error("====", e);
}
解决办法
改为map传参:HttpEntity<Map<String, String>> request = new HttpEntity<>(param, headers);
Map<String, String> param = new HashMap();
param.put("userName", "tom");
param.put("password", encrypt);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
HttpEntity<Map<String, String>> request = new HttpEntity<>(param, headers);
ResponseEntity<String> stringResponseEntity = null;
try {
stringResponseEntity = restTemplate.postForEntity("http://localhost:8009/xxx/userLoginAuth", request, String.class);
HttpStatus statusCode = stringResponseEntity.getStatusCode();
logger.info("===:{}", statusCode);
} catch (RestClientException e) {
logger.error("====", e);
}