根据天气接口获取其中的数据
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;
}
本文介绍了一种通过Java程序调用Seniverse API来获取上海实时天气数据的方法。使用Jsoup库进行HTTP请求,并解析返回的JSON数据以提取温度等关键信息。
1092

被折叠的 条评论
为什么被折叠?



