Java中获取实时气象信息的3种方法

 更新时间:2025年06月11日 10:47:03   作者:码喽Plus  
随着互联网的发展,越来越多的应用程序需要获取实时的天气信息来为用户提供更好的服务,这篇文章主要介绍了Java中获取实时气象信息的3种方法,文中通过代码介绍的非常详细,需要的朋友可以参考下

在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而定⭐⭐⭐⭐

到此这篇关于Java中获取实时气象信息的3种方法的文章就介绍到这了,更多相关Java获取实时气象信息内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java实现航空用户管理系统

    java实现航空用户管理系统

    这篇文章主要为大家详细介绍了java实现航空用户管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • 详解java基础--提示对话框的使用

    详解java基础--提示对话框的使用

    这篇文章主要介绍了java基础--提示对话框的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • Java Volatile应用单例模式实现过程解析

    Java Volatile应用单例模式实现过程解析

    这篇文章主要介绍了Java Volatile应用单例模式实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Springboot如何配置Scheduler定时器

    Springboot如何配置Scheduler定时器

    这篇文章主要介绍了Springboot如何配置Scheduler定时器问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03
  • SpringBoot如何读取resources目录下的文件

    SpringBoot如何读取resources目录下的文件

    这篇文章主要介绍了SpringBoot如何读取resources目录下的文件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • Java 方法签名详解及实例代码

    Java 方法签名详解及实例代码

    这篇文章主要介绍了 Java 方法签名详解及实例代码的相关资料,需要的朋友可以参考下
    2016-10-10
  • Java内省之Introspector解读

    Java内省之Introspector解读

    这篇文章主要介绍了Java内省之Introspector解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • java实现飞机大战游戏

    java实现飞机大战游戏

    这篇文章主要为大家详细介绍了java实现飞机大战游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-03-03
  • 详解JNA中的回调方法

    详解JNA中的回调方法

    这篇文章主要介绍了JNA中的回调方法,主要包括JNA 中的 Callback,callback 的应用,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2022-05-05
  • java中接口(interface)及使用方法示例

    java中接口(interface)及使用方法示例

    这篇文章主要介绍了java中接口(interface)及使用方法示例,涉及接口定义的简单介绍以及Java语言代码示例,具有一定借鉴价值,需要的朋友可以参考下。
    2017-11-11

最新评论