基于和风天气API获取七天天气状况的示例代码 使用java语言
时间: 2023-09-25 21:13:07 浏览: 159
ESP32获取和风天气
好的,这里是一个基于和风天气API获取七天天气状况的示例代码(使用Java语言):
```java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
public class WeatherForecast {
public static void main(String[] args) {
String api_key = "your_api_key";
String location = "北京";
String urlStr = "https://free-api.heweather.net/s6/weather/forecast?location="
+ location + "&key=" + api_key;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
throw new RuntimeException("HTTP response code: " + responseCode);
} else {
Scanner sc = new Scanner(conn.getInputStream());
String jsonString = "";
while (sc.hasNext()) {
jsonString += sc.nextLine();
}
sc.close();
JSONObject json = new JSONObject(jsonString);
JSONArray forecastArr = json.getJSONArray("HeWeather6")
.getJSONObject(0).getJSONArray("daily_forecast");
for (int i = 0; i < forecastArr.length(); i++) {
JSONObject forecast = forecastArr.getJSONObject(i);
String date = forecast.getString("date");
String cond_txt_d = forecast.getString("cond_txt_d");
String cond_txt_n = forecast.getString("cond_txt_n");
String tmp_max = forecast.getString("tmp_max");
String tmp_min = forecast.getString("tmp_min");
System.out.println(date + " 白天" + cond_txt_d + " 夜间" + cond_txt_n
+ ",最高温度 " + tmp_max + "℃,最低温度 " + tmp_min + "℃");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,需要将`your_api_key`替换为您自己的和风天气API的密钥。并且`location`参数可以修改为您所在城市的名称或者城市ID,以获取对应城市的天气数据。
执行上述代码将会输出七天的天气状况信息,包括日期、白天天气、夜间天气、最高温度和最低温度。
阅读全文