JAVA中获取实时气象信息的方法

在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&current_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 WebClientSpring Boot项目,异步支持视API而定⭐⭐⭐⭐

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值