使用RestTemplate始终拿不到预期的返回值

问题回顾
--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

Same as in Spring WebFlux

The spring-web module contains the HttpMessageConverter contract for reading and writing the body of HTTP requests and responses through InputStream and OutputStreamHttpMessageConverter 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") 注解

来源:使用RestTemplate始终拿不到预期的返回值 - SegmentFault 思否

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值