Java中獲取實(shí)時氣象信息的3種方法
在Java中獲取實(shí)時氣象信息,可以通過調(diào)用氣象API(如Open-Meteo、OpenWeatherMap等)實(shí)現(xiàn)。
方法1:使用 HttpClient(Java 11+)調(diào)用Open-Meteo API
Open-Meteo是一個免費(fèi)的天氣API,無需API密鑰即可使用。
public static void main(String[] args) {
double latitude = 39.9042; // 北京緯度
double longitude = 116.4074; // 北京經(jīng)度
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());
// 解析當(dāng)前天氣數(shù)據(jù)
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("當(dāng)前溫度: " + temperature + "°C");
System.out.println("風(fēng)速: " + windspeed + " km/h");
System.out.println("風(fēng)向: " + windDirection + "°");
} catch (Exception e) {
e.printStackTrace();
}
}輸出示例:
當(dāng)前溫度: 25.3°C
風(fēng)速: 12.5 km/h
風(fēng)向: 180°
方法2:使用 OkHttp 調(diào)用OpenWeatherMap API
OpenWeatherMap提供更詳細(xì)的天氣數(shù)據(jù),但需要API密鑰(免費(fèi)注冊)
使用到的依賴
<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);
// 解析天氣數(shù)據(jù)
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("當(dāng)前溫度: " + temperature + "°C");
System.out.println("濕度: " + humidity + "%");
System.out.println("天氣狀況: " + weatherDesc);
} catch (Exception e) {
e.printStackTrace();
}
}輸出示例:
當(dāng)前溫度: 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
}
}
總結(jié)
| 方法 | 適用場景 | 是否需要API密鑰 | 推薦指數(shù) |
|---|---|---|---|
| Open-Meteo | 免費(fèi)、簡單、全球數(shù)據(jù) | ? 不需要 | ???? |
| OpenWeatherMap | 更詳細(xì)數(shù)據(jù),但需注冊 | ? 需要 | ??? |
| Spring WebClient | Spring Boot項(xiàng)目,異步支持 | 視API而定 | ???? |
到此這篇關(guān)于Java中獲取實(shí)時氣象信息的3種方法的文章就介紹到這了,更多相關(guān)Java獲取實(shí)時氣象信息內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決idea中yml文件圖標(biāo)問題及自動提示失效的情況
這篇文章主要介紹了解決idea中yml文件圖標(biāo)問題及自動提示失效的情況,具有很好的價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
Java?中的?getDeclaredFields()使用與原理解析
在Java反射機(jī)制中,getDeclaredFields()用于獲取類的所有字段,包括私有字段,通過反射,可以在運(yùn)行時動態(tài)地獲取類的信息并操作其成員,本文詳細(xì)介紹了getDeclaredFields()的使用方法、工作原理以及最佳實(shí)踐,涵蓋了反射的基本概念、使用場景和注意事項(xiàng),感興趣的朋友一起看看吧2025-01-01
Java實(shí)現(xiàn)解析zip壓縮包并獲取文件內(nèi)容
這篇文章主要為大家詳細(xì)介紹了如何利用Java語言實(shí)現(xiàn)頁面上傳一個源碼壓縮包,后端將壓縮包解壓,并獲取每個文件中的內(nèi)容,感興趣的可以動手嘗試一下2022-07-07
通過反射注解批量插入數(shù)據(jù)到DB的實(shí)現(xiàn)方法
今天小編就為大家分享一篇關(guān)于通過反射注解批量插入數(shù)據(jù)到DB的實(shí)現(xiàn)方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
一步步教你JAVA如何優(yōu)化Elastic?Search
想要榨干Java操作Elasticsearch的所有性能潛力?本指南將一步步教你如何優(yōu)化Java與Elasticsearch的交互!從此,提升ES查詢速度、降低資源消耗不再是難題,趕快一起來探索Java?Elasticsearch優(yōu)化的秘訣吧!2024-01-01

