这里的天气属性有很多,可以根据自己的需求获取天气属性
这里用到了org.json的jar包,因为要使用XML属性解析数据,还有alibab.JAONObject的jar包
/**
* 天气预报-更新
* 定时任务,每5分钟获取一次天气信息
* @return
*/
@Scheduled(cron = "0 0/5 * * * ?")//0 0/5 * * * ? 5分钟执行一次
public void update() throws Exception{
try {
//定义list集合
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//定义map集合
Map<String, Object> map = new HashMap<String, Object>();
//实例化天气类
SWeather weatherinfo=new SWeather();
HttpClient client = HttpClientBuilder.create().build();
//获取天气信息的XML内容信息
String url = "http://flash.weather.com.cn/wmaps/xml/chongqing.xml"; // url:网址
HttpGet post=new HttpGet(url);
HttpResponse response =client.execute(post);
System.out.println(response);
BufferedReader rd= new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result=new StringBuffer();
String line="";
while ((line=rd.readLine())!=null){
result.append(line);
}
//通过org.json的依赖包,获取XML结构信息
org.json.JSONObject xmlJSONObj= XML.toJSONObject(result.toString());
//将Object信息转为String
String jsonStr = xmlJSONObj.toString();
com.alibaba.fastjson.JSONObject alijsonStr = com.alibaba.fastjson.JSONObject.parseObject(jsonStr);
//获取重庆信息
com.alibaba.fastjson.JSONObject info = alijsonStr.getJSONObject("chongqing");
//设定迭代器iter
Iterator iter = info.entrySet().iterator();
//通过while循环获取key和value值
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
//获取key的值
String key=entry.getKey().toString();
//获取value的值
String value=entry.getValue().toString();
//蒋value的值转为JSONArray
JSONArray jsonData2= JSONArray.parseArray(value);
//循环获取第一个为“重庆”的天气信息
for(int i=0;i<1;i++){
com.alibaba.fastjson.JSONObject jsonObj=jsonData2.getJSONObject(i);
//拼接天气温度
String temperature=jsonObj.getString("tem1")+"/"+jsonObj.getString("tem2")+"℃";
//拼接风力
map.put("temperature",temperature);// 天气
map.put("info",jsonObj.getString("stateDetailed"));// 天气
map.put("direct",jsonObj.getString("windDir"));// 风向
map.put("power",jsonObj.getString("windPower"));// 风力
map.put("humidity",jsonObj.getString("humidity")+"RH");//湿度
map.put("wid",jsonObj.getString("state2"));//天气类型
map.put("refreshTime",new Date());//刷新时间
//将map值放到list集合中
list.add(map);
//循环list集合,写入参数
for (int k = 0; k < list.size(); k++) {
weatherinfo.setWeatherId("1");
weatherinfo.setTemperature(list.get(k).get("temperature").toString());//温度
weatherinfo.setInfo(list.get(k).get("info").toString());//天气
weatherinfo.setPower(list.get(k).get("power").toString());//风力
weatherinfo.setHumidity(list.get(k).get("humidity").toString());//湿度
weatherinfo.setDirect(list.get(k).get("direct").toString());//风向
weatherinfo.setWid(list.get(k).get("wid").toString());//天气类型
weatherinfo.setRefreshTime(new Date());//刷新时间
}
//保存写入信息
weatherRepository.save(weatherinfo);
}
}
}catch (Exception e){
System.out.println(e);
}
}