基于Java实现的console控制台天气实时查询系统
简单易懂,适用于学习、课设等用途,该系统使用java编程,通过Http请求调用开源的天气查询API,实现了手动录入城市名称,实时查询某个城市天气信息功能。
功能介绍
- 支持手动录入城市名称
- 根据城市名称查询当前天气预报信息
技术栈
SpringBoot+Http请求
运行环境
IDEA+Jdk
效果演示
- 根据城市查询天气信息
示例代码
输入城市
/**
* 启动程序时会提示输入天气情况
* 查询完成后接着提示天气情况
*/
@PostConstruct
public void init(){
boolean flag=true;
while (flag){
Scanner sc=new Scanner(System.in);
System.out.println("请输入想要查询的城市:");
if (!sc.hasNext()){
flag=false;
}
String input = sc.next();
try {
selectCity(input);
} catch (Exception e) {
//e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
public void selectCity(String city){
JSONObject realWeather = WeatherUtil.getRealWeather(city);
System.out.println("》》》》实况天气《《《《");
System.out.println(realWeather.getStr("cityname")
+" 天气:"+ realWeather.getStr("weather")
+" 温度:"+ realWeather.getStr("temp")
+" 湿度:"+ realWeather.getStr("sd")
+" Pm2.5:"+realWeather.getStr("aqi_pm25")
);
JSONObject weather = WeatherUtil.getWeather(city);
System.out.println("》》》》当天天气《《《《");
System.out.println(weather.getStr("cityname")
+" 最低温度:"+ weather.getStr("tempn")
+" 最高温度:"+ weather.getStr("temp")
+" 风向:"+ weather.getStr("wd")
+" 风速:"+weather.getStr("ws")
);
JSONObject weatherZs = WeatherUtil.getWeatherZs(city);
System.out.println("小助手提示:"+weather.getStr("cityname")+"\n"
+" 紫外线:"+ weatherZs.getStr("uv_hint")+"\n"
+" 运动指数:"+ weatherZs.getStr("yd_hint")+"\n"
+" 干燥指数:"+ weatherZs.getStr("gz_des_s")+"\n"
+" 约会指数:"+ weatherZs.getStr("yh_hint")+" 理由:"+ weatherZs.getStr("yh_des_s")+"\n"
);
}
天气信息查询
public static String cityAreaId(String city){
if (cityJson==null){
//获取出所有城市的AreaId
JSONObject cityAreaId = getCity();
cityJson=cityAreaId;
}
//取出对应城市的areaid
String areaId = cityJson.getStr(city);
if (areaId==null){
throw new RuntimeException("该城市找不到AreaId");
}
return areaId;
}
/**
* 获取当天城市天气
* @param city
* @return
*/
public static JSONObject getWeather(String city){
//取出对应城市的areaid
String areaId = cityAreaId(city);
String WEATHER_URL="http://d1.weather.com.cn/dingzhi/";
String uri=WEATHER_URL+areaId+".html";
String res = HttpUtil.createGet(uri).timeout(10000).header("Referer", "http://www.weather.com.cn/").execute().body();
String resR = res.replace("var cityDZ"+areaId+" =", "");
String[] split = resR.split(";");
return JSONUtil.parseObj(split[0]).getJSONObject("weatherinfo");
}
最后
看到最后,感觉不错的话记得点赞收藏哦。感兴趣可扫码关注获取源码