java根据经纬度获取天气
时间: 2023-10-18 11:20:11 浏览: 185
要根据经纬度获取天气,可以使用第三方天气 API。以下是一种使用 OpenWeatherMap API 获取天气数据的示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONObject;
public class Weather {
public static void main(String[] args) {
try {
// 经纬度信息
double lat = 40.7128;
double lon = -74.0060;
// 调用 OpenWeatherMap API
String apiKey = "your_api_key";
String url = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + apiKey;
URLConnection conn = new URL(url).openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
// 解析 JSON 数据
JSONObject json = new JSONObject(sb.toString());
JSONObject main = json.getJSONObject("main");
double temp = main.getDouble("temp");
double feelsLike = main.getDouble("feels_like");
double humidity = main.getDouble("humidity");
String description = json.getJSONArray("weather").getJSONObject(0).getString("description");
// 打印天气信息
System.out.println("Temperature: " + temp + " K");
System.out.println("Feels like: " + feelsLike + " K");
System.out.println("Humidity: " + humidity + " %");
System.out.println("Description: " + description);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
需要替换代码中的 `your_api_key` 为你自己的 OpenWeatherMap API Key。此示例仅提供了温度、体感温度、湿度和天气描述等基本信息,你可以根据需要选择解析更多的 JSON 数据。
阅读全文