问题回顾
--spring versoion 5.1.5
在使用RestTemplate
进行第三方接口交互的时候,始终拿不到预期的返回值,以下为相关代码
main
public static void main(String[] args) throws Exception { RestTemplate restTemplate = new RestTemplate(); MessageRequestBody requestBody = new MessageRequestBody(); requestBody.setParam1("value1"); requestBody.setParam2("value2"); HttpEntity<Object> entity = new HttpEntity<>(requestBody); System.out.println(restTemplate.postForObject(url, entity, responseType)); }
Dto
@Data public static class MessageRequestBody { private String param1; private String param2; } @Data public static class MessageResponseBody { private int Ret; private String Msg; }
预期返回值
{ "Ret": 200, "Msg": "Success" }
实际返回值
{ "Ret": 0, "Msg": null }
一开始以为是第三方的问题,然后我用 postman
试过之后发现返回的是预期的值,随后开始了蛮长的自查之路
先是猜测 headers
中 Content-Type
未设定,并进行尝试,返回值并没有什么变化
随后把 MessageResponseBody
类型改为 String.class
发现返回值对了,这才知道是消息转换器的问题
以下为官方文档
Message Conversion
The spring-web
module contains the HttpMessageConverter
contract for reading and writing the body of HTTP requests and responses through InputStream
and OutputStream
. HttpMessageConverter
instances are used on the client side (for example, in the RestTemplate
) and on the server side (for example, in Spring MVC REST controllers).
Concrete implementations for the main media (MIME) types are provided in the framework and are, by default, registered with the RestTemplate
on the client side and with RequestMethodHandlerAdapter
on the server side (see Configuring Message Converters).
RestTemplate
在你没有配置 HttpMessageConverter
的时候会给你指定默认的消息转换器
而转换 MessageResponseBody
此对象的正是 MappingJackson2HttpMessageConverter
这个罪魁祸首
在映射 MessageResponseBody
时,自动把属性首字符转成了小写,导致跟 MessageResponseBody
的属性对不上,得到了一个默认值啥都没有的默认值
解决方案:
给 MessageResponseBody
的字段配置 @JsonProperty(value="Ret")
注解