根据天气接口获取其中的数据

时间:2021-05-30 14:37:11

根据天气接口获取其中的数据

public class WeatherService {

public HashMap<String, Object> getWeatherData() {
String weatherStr = "";
//String weatherUrl = "https://api.seniverse.com/v3/weather/now.json?key=sktgsqmnajlsyvqf&location=shanghai&language=zh-Hans&unit=c";
HashMap<String, Object> res = new HashMap<String, Object>();
try {
weatherStr = Jsoup.connect("https://api.seniverse.com/v3/weather/now.json?key=sktgsqmnajlsyvqf&location=shanghai&language=zh-Hans&unit=c").ignoreContentType(true).execute().body();
//使用Jsoup连接目标页面,并执行请求,获取服务器响应内容--页面内容(json)
} catch (IOException e) {
e.printStackTrace();
return res;
}
System.out.println("--------------------------------------------------"+weatherStr+"-");//打印页面内
//将获取的json数据进行转化成数组,然后获取其中的天气数据
JSONObject weatherArray;
JSONObject resultsJson;
JSONObject weatherDataArray = null;

weatherArray = JSONObject.fromObject(weatherStr);
resultsJson = (JSONObject) JSONArray.fromObject(weatherArray.get("results")).get(0);
weatherDataArray = (JSONObject) JSONArray.fromObject(resultsJson.get("now")).get(0);
String temperature = weatherDataArray.getString("temperature");
//String wind = weatherDataArray.getString("wind_speed");

res.put("temperature", temperature);
//res.put("wind", wind);


return res;
}