用Java的方式封装了一个天气的接口,查询了好多,要么是要收费的,要么需要使用官方的密匙Key。
总不能项目上线了还要告诉运维记得换个key吧,想想就就得不现实。
1、接口介绍
所以,小编列举了几个网站,供大家使用,不需要key,完全免费,绝无后顾之忧:
首先,当然是【国国家气象局】中天气预报提供的接口,总共三个:
- http://www.weather.com.cn/data/sk/101010100.html;
- http://www.weather.com.cn/data/cityinfo/101010100.html;
- http://m.weather.com.cn/data/101010100.html;(已停用!!)
注意:
上面url中的“101010100”是城市代码,这里指代“北京”的城市代码。只需要改变城市代码,就可以得到所在城市的天气信息。其中,最详细的信息来自第三个接口,但是该接口已经停用了。
第一个,第二个目前可用,但是查询的信息并不全,也不支持未来几天的天气预报等信息。
但是,实际业务中我们有必要检索一个天气数据既全面,有支持未来几天预告的API。
所以,再推荐几个来自【万年历】的天气预报查询接口,总结两个:
- http://wthrcdn.etouch.cn/weather_mini?city=北京;
- http://www.sojson.com/open/api/weather/json.shtml?city=北京;
这两个接口还有一个明显的优势:不需要维护城市代码,可以使用城市名称进行天气查询,非常nice。
第二个天气API详情介绍在 API 中心:http://www.sojson.com/api/weather.html ,该接口经常发生变化,若无法访问请访问官网查看最新地址。
所以,小编写一下【万年历】的第一个接口【wthrcdn.etouch.cn】的Demo:
2、使用方法
天气实体类:WeatherInfo
public class WeatherInfo {private String date; //时间private String week; //星期private String lunar; //农历时间private String cityname; //城市名private String weather; //天气private String temp; //当前温度private String highTemp; //最低温度private String lowTemp; //当前温度private String tips; //小提示... (省略get,set,toString方法)}
天气工具类:WeatherUtil
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.zip.GZIPInputStream;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;/*** @author :tjm* 通过get请求向网站:http://wthrcdn.etouch.cn/weather_mini 获取某个 城市的天气状况数据,数据格式是Json* @date :Created in 2020/3/9 13:55**/
public class WeatherUtils {private static String weatherUrl = "http://wthrcdn.etouch.cn/weather_mini?city=";/*** 通过城市名称获取该城市的天气信息*/public static String GetWeatherData(String cityname) {StringBuilder sb = new StringBuilder();BufferedReader reader = null;try {URL url = new URL(weatherUrl + cityname);URLConnection conn = url.openConnection();InputStream is = conn.getInputStream();GZIPInputStream gzin = new GZIPInputStream(is);// 设置读取流的编码格式,自定义编码InputStreamReader isr = new InputStreamReader(gzin, "utf-8");reader = new BufferedReader(isr);String line = null;while((line = reader.readLine()) != null){sb.append(line + " ");}reader.close();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (MalformedURLException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return sb.toString();}/*** 将JSON格式数据进行解析 ,返回一个weather对象*/public static WeatherInfo GetWeather(String weatherInfobyJson){JSONObject dataOfJson = JSONObject.fromObject(weatherInfobyJson); // json天气数据if(dataOfJson.getInt("status") != 1000){return null;}// 创建WeatherInfo对象,提取所需的天气信息WeatherInfo weatherInfo = new WeatherInfo();// 获取当前日期:日期、星期Calendar cal = Calendar.getInstance(); // Calendar类的实例化SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日"); // 时间的格式化weatherInfo.setDate(sdf1.format(cal.getTime())); // 时间SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE");weatherInfo.setWeek(sdf2.format(cal.getTime())); // 星期// 从json数据中提取数据:城市、温度、小提醒dataOfJson = JSONObject.fromObject(dataOfJson.getString("data"));weatherInfo.setCityname(dataOfJson.getString("city")); // 城市weatherInfo.setTemp(dataOfJson.getString("wendu")); // 温度weatherInfo.setTips(dataOfJson.getString("ganmao")); // 小提示// 获取今天的天气预报信息:最高温度、最低温度、天气JSONArray forecast = dataOfJson.getJSONArray("forecast");JSONObject result = forecast.getJSONObject(0);weatherInfo.setHighTemp(result.getString("high").substring(2)); // 最高气温weatherInfo.setLowTemp(result.getString("low").substring(2)); // 最低气温weatherInfo.setWeather(result.getString("type")); // 天气return weatherInfo;}}
测试代码:test
public class Test {public static void main(String[] args){String info = WeatherUtils.GetWeatherData("天津");System.out.println("1.预测结果:" + info); // 全部天气数据,含预测WeatherInfo weatherinfo = WeatherUtils.GetWeather(info);System.out.println("2.今天天气:" + weatherinfo.toString()); // 当天天气数据}}
结果:
1.预测结果:
{
"data": {
"yesterday": {
"date": "9日星期一",
"high": "高温 8℃",
"fx": "东北风",
"low": "低温 1℃",
"fl": "<![CDATA[4-5级]]>",
"type": "小雨"
},
"city": "天津",
"forecast": [
{
"date": "10日星期二",
"high": "高温 13℃",
"fengli": "<![CDATA[4-5级]]>",
"low": "低温 3℃",
"fengxiang": "西北风",
"type": "晴"
},
{
"date": "11日星期三",
"high": "高温 16℃",
"fengli": "<![CDATA[4-5级]]>",
"low": "低温 4℃",
"fengxiang": "西南风",
"type": "晴"
},
{
"date": "12日星期四",
"high": "高温 16℃",
"fengli": "<![CDATA[4-5级]]>",
"low": "低温 2℃",
"fengxiang": "东北风",
"type": "多云"
},
{
"date": "13日星期五",
"high": "高温 8℃",
"fengli": "<![CDATA[3-4级]]>",
"low": "低温 0℃",
"fengxiang": "北风",
"type": "多云"
},
{
"date": "14日星期六",
"high": "高温 10℃",
"fengli": "<![CDATA[4-5级]]>",
"low": "低温 2℃",
"fengxiang": "西北风",
"type": "晴"
}
],
"ganmao": "天冷风大且昼夜温差也很大,易发生感冒,请注意适当增减衣服。",
"wendu": "9"
},
"status": 1000,
"desc": "OK"
}
2.今天天气:
WeatherInfo{date='2020年03月10日', week=星期二, lunar='null', cityname='天津', weather='晴', temp='9', highTemp=' 13℃', lowTemp=' 3℃', tips='天冷风大且昼夜温差也很大,易发生感冒,请注意适当增减衣服。'}
注意:
- 预测结果:是该API获取的全部数据,包含昨天,今天,以及未来4天的天气情况;
- 今天天气:是从预测结果JSON数据中取出来,封装成对象的数据,在data.forecast下的第一条记录中。
更多精彩,请关注我的"今日头条号":Java云笔记
随时随地,让你拥有最新,最便捷的掌上云服务