和风 天气接口 java代码后台获取:
这里要注意的是,要对流进行解压缩.
private final static String weatherUrl = "https://devapi.qweather.com/v7/weather/3d?location=**&key=**";
/**
* 获取最新的天气数据
*
* @param url
* @return
*/
private String getWeatherJson(String url) {
try {
URLConnection uc = new URL(url).openConnection();
InputStream is = uc.getInputStream();
GZIPInputStream gzip = new GZIPInputStream(is);
InputStreamReader isr = new InputStreamReader(gzip, "utf-8");
BufferedReader reader = new BufferedReader(isr);
StringBuffer jsonBuffer = new StringBuffer();
String line = null;
while (null != (line = reader.readLine())) {
jsonBuffer.append(line);
}
reader.close();
return jsonBuffer.toString();
} catch (IOException e) {
return null;
}
}
ps: 公司为了白嫖天气接口,想出的办法是每天掉个几次,存在数据库中,再传给前端处理,可是在处理过程中拿到的JSON数据总是乱码,最后发现是没有解压缩,也就是GZIPInputStream.