输入城市名称,根据名称查询code。code需要自己整理,爬取的中国天气网的数据。
public Result getWeatherByNameTwo(String cityName) {
//code先前整理,code和name一一对应
WeatherCity city = weatherCityDao.getByName(cityName);
if (AppUtil.isNull(city)){
return Result.newFailed("暂未获取到当前城市天气");
}
Object obj = JedisPlus.getObjFromJson(StringUtil.replaceStr(Consts.JEDIS_CITY_WEATHER,cityName), Object.class);
if (AppUtil.isNull(obj)){
try {
String url = "http://www.weather.com.cn/weather1d/" + city.getCityCode() + ".shtml";
org.jsoup.nodes.Document document = Jsoup.connect(url).get();
org.jsoup.nodes.Element element = document.getElementById("hidden_title");
String val = element.val();
String[] split = val.split(" ");
Map<String,String> map = new HashMap<>(2);
map.put("temperature", split[2]);
map.put("weather", split[1]);
obj = JSONObject.toJSON(map);
//获取一天中剩余的秒数
Integer seconds = DateUtils.getDayRemainingTime(new Date());
JedisPlus.setObjToJson(StringUtil.replaceStr(Consts.JEDIS_CITY_WEATHER,cityName), obj, seconds);
}catch (Exception e){
LogUtil.error("解析【"+cityName+"】天气数据异常",e);
return Result.newFailed("当前城市天气获取异常,请稍后");
}
}
return Result.newSuccess(obj);
}
需要code整理好的sql,也可以在这里下载:
https://download.csdn.net/download/qq_41443299/11177348