天气预报接口服务使用的聚合数据提供的免费接口,每天可以100次免费调用。可以通过https://www.juhe.cn/docs/api/id/73注册及开通
接口地址:http://apis.juhe.cn/simpleWeather/query
返回格式:json
请求方式:http get/post
请求示例:http://apis.juhe.cn/simpleWeather/query?city=%E8%8B%8F%E5%B7%9E&key=
接口备注:通过城市名称或城市ID查询天气预报情况
city string 要查询的城市名称/id,城市名称如:温州、上海、北京,需要utf8 urlencode
key string 在个人中心->我的数据,接口名称上方查看
名称 | 类型 | 说明 |
---|---|---|
error_code | int | 返回码,0为查询成功 |
reason | string | 返回说明 |
result | string | 返回结果集 |
realtime | - | 当前天气详情情况 |
info | string | 天气情况,如:晴、多云 |
wid | string | 天气标识id,可参考小接口2 |
temperature | string | 温度,可能为空 |
humidity | string | 湿度,可能为空 |
direct | string | 风向,可能为空 |
power | string | 风力,可能为空 |
aqi | string | 空气质量指数,可能为空 |
future | - | 近5天天气情况 |
date | string | 日期 |
temperature | string | 温度,最低温/最高温 |
weather | string | 天气情况 |
direct | string | 风向 |
{
"reason": "查询成功",
"result": {
"city": "苏州",
"realtime": {
"temperature": "4",
"humidity": "82",
"info": "阴",
"wid": "02",
"direct": "西北风",
"power": "3级",
"aqi": "80"
},
"future": [
{
"date": "2019-02-22",
"temperature": "1/7℃",
"weather": "小雨转多云",
"wid": {
"day": "07",
"night": "01"
},
"direct": "北风转西北风"
},
{
"date": "2019-02-23",
"temperature": "2/11℃",
"weather": "多云转阴",
"wid": {
"day": "01",
"night": "02"
},
"direct": "北风转东北风"
},
{
"date": "2019-02-24",
"temperature": "6/12℃",
"weather": "多云",
"wid": {
"day": "01",
"night": "01"
},
"direct": "东北风转北风"
},
{
"date": "2019-02-25",
"temperature": "5/12℃",
"weather": "小雨转多云",
"wid": {
"day": "07",
"night": "01"
},
"direct": "东北风"
},
{
"date": "2019-02-26",
"temperature": "5/11℃",
"weather": "多云转小雨",
"wid": {
"day": "01",
"night": "07"
},
"direct": "东北风"
}
]
},
"error_code": 0
}
例如:
// 连接中央气象台的API
Object weather = redisTemplate.opsForValue().get("weather");
if (weather == null) {
URL url = null;
try {
url = new URL(
"http://apis.juhe.cn/simpleWeather/query?city=%E6%9E%A3%E5%BA%84&key=----------------------");
}
catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connectionData = null;
try {
connectionData = url.openConnection();
}
catch (IOException e) {
e.printStackTrace();
}
connectionData.setConnectTimeout(1000);
Map<String, Object> map = new HashMap<String, Object>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
String datas = sb.toString();
JSONObject jsonData = JSON.parseObject(datas);
String result = jsonData.getString("result");
HashMap map1 = JSON.parseObject(result, HashMap.class);
redisTemplate.opsForValue().setIfAbsent("weather", map1, 3600, TimeUnit.SECONDS);
return map1;
}
catch (SocketTimeoutException e) {
System.out.println("连接超时");
}
catch (FileNotFoundException e) {
System.out.println("加载文件出错");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return map;