网站首页> 博客> RestTemplate中文乱码

RestTemplate中文乱码

好文 1868
黑园皛皛
黑园皛皛 2020-03-19
收藏

【问题】:在做springboot项目本地test测试时发现出现请求参数和返回值乱码问题,过滤器和yml文件中设置的utf-8编码都不起左右,可是使用postman请求时发现请求参数和返回值编码正常,一顿debug找原因最后发现是restemplate出现乱码。

【解决】:增加了 restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));代码,意思是设置restemplate编码为utf-8,因为不设置此编码,restemplate底层是默认使用ISO-8859-1编码,所以在请求发送出去后编码格式并不是utf-8,此时在接收端即使用了编码过滤器也没有作用。

【代码】:

@Test
    public void getGoodsContent() {
        RestTemplate restTemplate = new RestTemplate();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        String paramter = "{'cityName': '北京'}";
        HttpEntity entity = new HttpEntity(paramter);

        String json = restTemplate.postForObject("http://localhost:", entity, String.class);
        System.out.println(json);
}

@Test
    public void getGoodsContent() {
        RestTemplate restTemplate = new RestTemplate();
        // 设置restemplate编码为utf-8
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        String paramter ="{'cityName': '北京'}";
        HttpEntity entity = new HttpEntity(paramter);

        String json = restTemplate.postForObject("http://localhost:", entity, String.class);
        System.out.println(json);
}

  • 没有任何评论
个评论
黑园皛皛

黑园皛皛 (白银)

251金币 (1)粉丝 (2)源码

梦得君知曰本命,回首相忆一欣然

 

加入微信群,不定期分享源码和经验
签到活跃榜 连续签到送额外金币
最新博客
校园跑腿系统外卖系统软件平台大学生创业平台搭建 461
壹脉销客智能名片CRM系统小程序可二开源码交付部署 450
为啥没搞了 650
Nginx 的 5 大应用场景,太实用了! 929
CentOS 8-stream 安装Postgresql 详细教程 1091
JAVA智慧校园管理系统小程序源码 电子班牌 Sass 模式 1052
Java智慧校园系统源码 智慧校园源码 智慧学校源码 智慧校园管理系统源码 小程序+电子班牌 799
Java智慧校园系统源码 智慧校园源码 智慧学校源码 智慧校园管理系统源码 小程序+电子班牌 778
致远OA权限 1270
发博客会有金币吗 812