在Java中获取实时气象信息,可以通过调用气象API(如Open-Meteo、OpenWeatherMap等)实现。
方法1:使用 HttpClient
(Java 11+)调用Open-Meteo API
Open-Meteo是一个免费的天气API,无需API密钥即可使用。
public static void main(String[] args) {
double latitude = 39.9042; // 北京纬度
double longitude = 116.4074; // 北京经度
String apiUrl = String.format(
"https://api.open-meteo.com/v1/forecast?latitude=%.4f&longitude=%.4f¤t_weather=true",
latitude, longitude
);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(response.body());
// 解析当前天气数据
JsonNode currentWeather = rootNode.path("current_weather");
double temperature = currentWeather.path("temperature").asDouble();
double windspeed = currentWeather.path("windspeed").asDouble();
int windDirection = currentWeather.path("winddirection").asInt();
System.out.println("当前温度: " + temperature + "°C");
System.out.println("风速: " + windspeed + " km/h");
System.out.println("风向: " + windDirection + "°");
} catch (Exception e) {
e.printStackTrace();
}
}
输出示例:
当前温度: 25.3°C
风速: 12.5 km/h
风向: 180°
方法2:使用 OkHttp
调用OpenWeatherMap API
OpenWeatherMap提供更详细的天气数据,但需要API密钥(免费注册)
使用到的依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
public static void main(String[] args) {
String apiKey = "YOUR_API_KEY"; // 替换为你的API密钥
String city = "Beijing";
String apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey + "&units=metric";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(apiUrl)
.build();
try {
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(responseBody);
// 解析天气数据
double temperature = rootNode.path("main").path("temp").asDouble();
double humidity = rootNode.path("main").path("humidity").asDouble();
String weatherDesc = rootNode.path("weather").get(0).path("description").asText();
System.out.println("当前温度: " + temperature + "°C");
System.out.println("湿度: " + humidity + "%");
System.out.println("天气状况: " + weatherDesc);
} catch (Exception e) {
e.printStackTrace();
}
}
输出示例:
当前温度: 26.5°C 湿度: 65% 天气状况: 多云
方法3:使用 Spring WebClient
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
public class WeatherService {
private final WebClient webClient;
public WeatherService() {
this.webClient = WebClient.create("https://api.open-meteo.com");
}
public Mono<String> getCurrentWeather(double latitude, double longitude) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/v1/forecast")
.queryParam("latitude", latitude)
.queryParam("longitude", longitude)
.queryParam("current_weather", true)
.build())
.retrieve()
.bodyToMono(String.class);
}
public static void main(String[] args) {
WeatherService service = new WeatherService();
service.getCurrentWeather(39.9042, 116.4074)
.subscribe(System.out::println);
}
}
输出示例:
{
"latitude": 39.9042,
"longitude": 116.4074,
"current_weather": {
"temperature": 25.3,
"windspeed": 12.5,
"winddirection": 180
}
}
总结
方法 | 适用场景 | 是否需要API密钥 | 推荐指数 |
---|---|---|---|
Open-Meteo | 免费、简单、全球数据 | ❌ 不需要 | ⭐⭐⭐⭐ |
OpenWeatherMap | 更详细数据,但需注册 | ✅ 需要 | ⭐⭐⭐ |
Spring WebClient | Spring Boot项目,异步支持 | 视API而定 | ⭐⭐⭐⭐ |