答案:通过调用OpenWeatherMap API获取天气数据,使用HttpURLConnection发送请求,JSON解析后展示城市、温度、湿度和天气状况。

要实现一个简易的天气查询应用,核心是通过调用公开的天气API获取数据,并在Java程序中解析和展示。整个过程不复杂,只要掌握HTTP请求、JSON解析和基础的面向对象设计即可。
目前有许多提供免费额度的天气服务,比如:
以 OpenWeatherMap 为例,访问其官网注册账号,获取一个API Key,之后可通过如下URL请求数据:
http://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=YOUR_API_KEY&units=metricJava中可以使用java.net.HttpURLConnection来发起GET请求。以下是一个简单的请求封装:
立即学习“Java免费学习笔记(深入)”;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherClient {
private static final String API_KEY = "your_api_key_here";
private static final String BASE_URL = "http://api.openweathermap.org/data/2.5/weather";
public String getWeatherData(String city) throws Exception {
String urlString = BASE_URL + "?q=" + city + "&appid=" + API_KEY + "&units=metric";
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
}
}
天气API返回的是JSON格式数据,可以用org.json库来解析。添加Maven依赖:
然后解析关键字段:
import org.json.JSONObject;
public void showWeather(String city) {
try {
String jsonResponse = getWeatherData(city);
JSONObject obj = new JSONObject(jsonResponse);
String cityName = obj.getString("name");
double temperature = obj.getJSONObject("main").getDouble("temp");
int humidity = obj.getJSONObject("main").getInt("humidity");
String weatherDesc = obj.getJSONArray("weather").getJSONObject(0).getString("description");
System.out.println("城市: " + cityName);
System.out.println("温度: " + temperature + "°C");
System.out.println("湿度: " + humidity + "%");
System.out.println("天气状况: " + weatherDesc);
} catch (Exception e) {
System.out.println("无法获取天气信息,请检查城市名称或网络连接。");
}
}
写一个主类调用上述方法:
public class Main {
public static void main(String[] args) {
WeatherClient client = new WeatherClient();
client.showWeather("Shanghai");
}
}
运行后会输出类似:
城市: Shanghai基本上就这些。只要API能通,JSON结构稳定,这个小应用就能正常工作。你可以进一步扩展功能,比如支持城市列表输入、定时刷新、图形界面(Swing/JavaFX)等。不复杂但容易忽略细节,比如异常处理和编码问题。保持简洁,先跑通再优化。
以上就是如何在Java中实现简易天气查询应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号