it编程 > 编程语言 > Java

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

9人参与 2025-06-11 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而定⭐⭐⭐⭐

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

(0)

您想发表意见!!点此发布评论

推荐阅读

java导出Echarts图表的示例代码(柱状图/饼形图/折线图)

06-11

Java类加载器ClassLoader详解

06-11

Springboot项目由JDK8升级至JDK17详细教程

06-11

java的Stream流处理示例小结

06-11

java获取压缩文件中的XML并解析保存到数据库

06-11

SpringBoot Java通过API的方式调用腾讯智能体(腾讯元宝)代码示例

06-11

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论