1.问题背景:服务A使用RestTemplate发送数据到服务B的接口,B是使用实体类对象进行接收的,但是接收到的所有参数都为空,需要增加@RequestBody才有数据:
发送方A:
public <T> T post(String url, Object requestObject, Class<T> responseType) {
RestTemplate restTemplate=new RestTemplate();
return restTemplate.postForObject(url, requestObject, responseType);
}
接收方B:
@RequestMapping("/sendMsg")
public String sendMsg(CustomerServiceMsg c) {
return "";//此时接收到的c的所有参数都为空
}
2.解决方案:
1. 接收方B的接口增加:@RequestBody
@RequestMapping("/sendMsg")
public String sendMsg(@RequestBody CustomerServiceMsg c) {
return "";
}
2.发送方A的接口改成如下:
public <T> T post(String url, Object obj, Class<T> responseType) {
//对中文格式数据进行处理
FormHttpMessageConverter fc= new FormHttpMessageConverter();
StringHttpMessageConverter stringConverter= new StringHttpMessageConverter(StandardCharsets.UTF_8); List<HttpMessageConverter<?>> partConverters= new ArrayList<>();
partConverters.add(stringConverter);
partConverters.add(new ResourceHttpMessageConverter());
fc.setPartConverters(partConverters);
restTemplate.getMessageConverters().addAll(Arrays.asList(fc, new MappingJackson2HttpMessageConverter()));
return (T) restTemplate.postForEntity(url, obj2Map(obj), responseType);
}
public MultiValueMap<String, Object> obj2Map(Object obj) {
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
map.add(field.getName(), field.get(obj));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}