首页 > 其他分享 >Spring RestTemplate 调用天气预报接口乱码的解决

Spring RestTemplate 调用天气预报接口乱码的解决

时间:2023-06-04 12:04:31浏览次数:44  
标签:String Spring RestTemplate 乱码 weather restTemplate new class


Spring RestTemplate 调用天气预报接口可能遇到中文乱码的问题,解决思路如下。

问题出现

我们在网上找了一个免费的天气预报接口 http://wthrcdn.etouch.cn/weather_mini?citykey=101280601。我们希望调用该接口,并将返回的数据解析为 JSON 格式。

核心业务逻辑如下:

private WeatherResponse doGetWeatherData(String uri) {

    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);

    String strBody = null;

    if (response.getStatusCodeValue() == 200) {
        strBody = response.getBody();
    }

    ObjectMapper mapper = new ObjectMapper();
    WeatherResponse weather = null;

    try {
        weather = mapper.readValue(strBody, WeatherResponse.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return weather;
}

在浏览器里面访问该接口都挺正常。如下图所示:

Spring RestTemplate 调用天气预报接口乱码的解决_Spring

但在纯 Spring 应用里面,尝试使用 RestTemplate 来调用,结果解析数据为 JSON 失败,因为数据有乱码。如下图所示:

Spring RestTemplate 调用天气预报接口乱码的解决_RestTemplate_02

尝试进行编码转换

一开始,我们认为这可能是对方转过来的数据不是 UTF-8 导致的,所以,尝试加入了消息转换器。

@Configuration
public class RestConfiguration {

    @Bean  
    public RestTemplate restTemplate() { 
        RestTemplate restTemplate = new RestTemplate(); 
        restTemplate.getMessageConverters().set(1, 
                new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 支持中文编码
        return restTemplate;
    }

}

StringHttpMessageConverter 默认是 ISO_8859_1,所以我们设置为了 UTF_8。

再次执行,发现仍然是乱码。

找到问题的根源

这一次我没有再瞎猜了,而是仔细观察了 HTTP 的请求协议。发现消息头里面的蛛丝马迹:

Spring RestTemplate 调用天气预报接口乱码的解决_Spring Boot_03

原来,数据是经过 GZIP 压缩过的。默认情况下, RestTemplate 使用的是 JDK 的 HTTP 调用器,并不支持 GZIP 解压,难怪解析不了。

解决方案

既然找到了问题所在,解决起来就简单了。主要考虑了以下几种方案。

1. 编写 GIZP 工具类

处理 Gizp 压缩的数据的工具类如下:

/**
 * Welcome to https://waylau.com
 */
package com.waylau.spring.mvc.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

/**
 * String Util.
 * 
 * @since 1.0.0 2018年3月27日
 * @author <a href="https://waylau.com">Way Lau</a>
 */
public class StringUtil {

    /**
     * 处理 Gizp 压缩的数据.
     * 
     * @param str
     * @return
     * @throws IOException
     */
    public static String conventFromGzip(String str) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in;
        GZIPInputStream gunzip = null;

        in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
        gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }

        return out.toString();
    }
}

核心业务逻辑如下:

private WeatherResponse doGetWeatherData(String uri) {

    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
    String strBody = null;

    if (response.getStatusCodeValue() == 200) {
        try {
            strBody = StringUtil.conventFromGzip(response.getBody());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ObjectMapper mapper = new ObjectMapper();
    WeatherResponse weather = null;

    try {
        weather = mapper.readValue(strBody, WeatherResponse.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return weather;
}

2. 使用 Apache HttpClient

使用 Apache HttpClient 作为 REST 客户端。Apache HttpClient 内置了对于 GZIP 的支持

@Configuration
public class RestConfiguration {

    @Bean  
    public RestTemplate restTemplate() { 
        RestTemplate restTemplate = new RestTemplate(
                new HttpComponentsClientHttpRequestFactory()); // 使用HttpClient,支持GZIP
        restTemplate.getMessageConverters().set(1, 
                new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 支持中文编码
        return restTemplate;
    }

}

核心业务逻辑如下:

private WeatherResponse doGetWeatherData(String uri) {

    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);

    String strBody = null;

    if (response.getStatusCodeValue() == 200) {
        strBody = response.getBody();
    }

    ObjectMapper mapper = new ObjectMapper();
    WeatherResponse weather = null;

    try {
        weather = mapper.readValue(strBody, WeatherResponse.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return weather;
}

当然,使用该方案,需要引入 Apache HttpClient 的依赖。

最终效果,完美!

Spring RestTemplate 调用天气预报接口乱码的解决_Spring Cloud_04

在 Spring Boot 中所使用的差异

也有学员问到,为啥我在“基于Spring Cloud的微服务实战”课程中,没有同样也是使用 RestTemplate, 调用同样的接口,为啥没有出现乱码的问题?

其实,细心的学员应该发现,在课程中,我们同样也是使用了 Apache HttpClient,由于 Spring Cloud 本身也是基于 Spring Boot 来构建的,所以屏蔽了很多消息转换的细节而言。

以下是 Spring Boot 中通过 RestTemplateBuilder 来构建 RestTemplate 的方式:

@Configuration
public class RestConfiguration {

    @Autowired
    private RestTemplateBuilder builder;

    @Bean
    public RestTemplate restTemplate() {
        return builder.build();
    }

}

所以学习编码,知其然要知其所以然!

源码

参考引用:


标签:String,Spring,RestTemplate,乱码,weather,restTemplate,new,class
From: https://blog.51cto.com/u_9427273/6410312

相关文章

  • 踩坑|以为是Redis缓存没想到却是Spring事务!
    前言  最近碰到了一个Bug,折腾了我好几天。并且这个Bug不是必现的,出现的概率比较低。一开始我以为是旧数据的问题,就让测试重新生成了一下数据,重新测试。由于后面几轮测试均未出现,我也就没太在意。  可惜好景不长,测试反馈上次的问题又出现了。于是我立马着手排查,根据日志的表......
  • 聊聊Spring Cloud Gateway
    网关概述整体来看,网关有点类似于门面,所有的外部请求都会先经过网关这一层。网关不仅只是做一个请求的转发及服务的整合,有了网关这个统一的入口之后,它还能提供以下功能。针对所有请求进行统一鉴权、限流、熔断、日志。协议转化。针对后端多种不同的协议,在网关层统一处理后以HT......
  • (五)Spring源码解析:ApplicationContext源码解析
    一、概述1.1>整体概览在前面的内容中,我们针对BeanFactory进行了深度的分析。那么,下面我们将针对BeanFactory的功能扩展类ApplicationContext进行深度的分析。ApplicationConext与BeanFactory的功能相似,都是用于向IOC中加载Bean的。由于ApplicationConext的功能是大于BeanFactory的......
  • 《面试1v1》Spring循环依赖
    我是javapub,一名Markdown程序员从......
  • 《面试1v1》SpringMVC
    我是javapub,一名Markdown程序员从......
  • 《面试1v1》Spring基础
    我是javapub,一名Markdown程序员从......
  • 《面试1v1》SpringBean生命周期
    我是javapub,一名Markdown程序员从......
  • Spring Boot 整合 分布式搜索引擎 Elastic Search 实现 我附近的、酒店竞排
    文章目录⛄引言一、我附近的酒店⛅需求分析⚡源码编写二、酒店竞价排名⌚需求分析⏰修改搜索业务✅效果图⛵小结⛄引言本文参考黑马分布式ElasticsearchElasticsearch是一款非常强大的开源搜索引擎,具备非常多强大功能,可以帮助我们从海量数据中快速找到需要的内容一、我附近的酒......
  • 搭建一个属于自己的springboot项目
    一、确定环境最近公司要上个新系统,指定由我来带两个人进行开发,既然是新项目,那么项目搭建的事就落到我的头上了。现在都是使用springboot进行开发,为此我搭环境使用的是springboot,具体java环境如下,使用springboot的版本是2.3.3.RELEASE。使用maven进行项目管理,总结下,我使用到的......
  • 大件货运系统源码,技术架构:spring boot、mybatis、redis、vue、element-ui
    网络货运平台源码网络货运平台的功能网络货运是指利用互联网平台,通过物流配送的方式进行商品销售和物流运输的一种新型商业模式。这种模式将传统的货运模式与互联网技术相结合,通过网络平台进行交易、物流配送和结算等一系列流程,从而实现货物的快速、高效、便捷地运输。技术架构:spr......