问题场景:
公司项目数据分析比对历史天气情况(越精确越好,和风提供了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问题都可以这么解决。
问题很简单,对于第三方接口对接经常会出现这种莫名奇妙的问题,后面看和风的文档里也没有说明,最后在和风的文档入口有说明,第三发接口文档一定要细看。
另和风示例代码可以更新了。