和风天气API调用结果乱码

问题场景:

公司项目数据分析比对历史天气情况(越精确越好,和风提供了10天每小时的数据基本能满足要求。当然用爬虫爬取气象网站数据也是可以的,但由于是企业项目,为避免不必要麻烦还是选择使用第三方接口数据)


问题描述

通过和风开发文档和提供的github示例代码(这里使用的是java),调用接口成功返回数据却是乱码,但浏览器get请求接口却没有乱码。


原因分析:

打开浏览器开发者工具获取请求发现响应头包含content-encoding:gzip
问题找到了返回结果数据被gzip加密了


解决方案:

public static void main(String[] args) throws Exception {
	String url = "https://geoapi.qweather.com/v2/city/lookup?location=beij&key=你的KEY"
	RestTemplate restTemplate = new RestTemplate();
	byte[] oResult = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class).getBody();
    String unGZipResult = unGZip(oResult);
    System.out.println(unGZipResult);
}

public static String unGZip(byte[] oResult) {
    try (InputStream inputStream = new ByteArrayInputStream(oResult);
         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) {
        byte[] buf = new byte[4096];
        int len = -1;
        while ((len = gzipInputStream.read(buf, 0, buf.length)) != -1) {
            byteArrayOutputStream.write(buf, 0, len);
        }
        return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new EnhanceRuntimeException(e);
    }
}

总结:

content-encoding:gzip问题都可以这么解决。
问题很简单,对于第三方接口对接经常会出现这种莫名奇妙的问题,后面看和风的文档里也没有说明,最后在和风的文档入口有说明,第三发接口文档一定要细看。
另和风示例代码可以更新了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值