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

要实现一个简易的天气查询应用,核心是通过调用公开的天气API获取数据,并在Java程序中解析和展示。整个过程不复杂,只要掌握HTTP请求、JSON解析和基础的面向对象设计即可。
选择合适的天气API
目前有许多提供免费额度的天气服务,比如:
- OpenWeatherMap:注册后可获得API Key,支持实时天气、预报等。
- WeatherAPI:功能全面,文档清晰,适合初学者。
- 中国天气网(和风天气):中文支持好,适合国内城市查询。
以 OpenWeatherMap 为例,访问其官网注册账号,获取一个API Key,之后可通过如下URL请求数据:
http://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=YOUR_API_KEY&units=metric发送HTTP请求并获取响应
Java中可以使用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();
}
}
解析JSON数据并展示结果
天气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温度: 24.5°C
湿度: 67%
天气状况: partly cloudy
基本上就这些。只要API能通,JSON结构稳定,这个小应用就能正常工作。你可以进一步扩展功能,比如支持城市列表输入、定时刷新、图形界面(Swing/JavaFX)等。不复杂但容易忽略细节,比如异常处理和编码问题。保持简洁,先跑通再优化。










