答案:开发Java天气查询应用需调用和风天气API获取JSON数据并解析展示。首先注册API获取密钥,通过HTTP客户端发送请求,使用JSONObject解析返回结果,输出城市气温、天气状况等信息,结合命令行输入实现简单交互,适合初学者掌握网络通信与数据处理基础。

开发一个简易的天气查询应用,核心在于获取网络API数据并解析展示。Java作为成熟的后端语言,非常适合实现这类HTTP请求与JSON处理任务。下面从需求分析到代码实现,一步步带你完成这个小项目。
我们要做一个命令行版的天气查询工具,用户输入城市名称,程序返回该城市的实时气温、天气状况、湿度等基本信息。
关键点包括:
推荐使用和风天气或OpenWeatherMap,它们都提供免费层级的API服务。
立即学习“Java免费学习笔记(深入)”;
以和风天气为例:
使用 Maven 管理项目,在 pom.xml 中加入:
<dependencies>
<!-- HTTP 客户端 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<pre class="brush:php;toolbar:false;"><!-- JSON 解析 -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230618</version>
</dependency>创建 WeatherApp.java 文件:
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
<p>public class WeatherApp {</p><pre class="brush:php;toolbar:false;">private static final String API_KEY = "your_api_key_here"; // 替换为你的Key
private static final String BASE_URL = "https://devapi.qweather.com/v7/weather/now";
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("请传入城市名称");
return;
}
String city = args[0];
String locationId = getLocationId(city); // 实际项目中需通过地理编码接口转换
String url = BASE_URL + "?location=" + locationId + "&key=" + API_KEY;
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
String jsonStr = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(jsonStr);
JSONObject now = json.getJSONObject("now");
System.out.println("城市: " + city);
System.out.println("温度: " + now.getString("temp") + "℃");
System.out.println("天气: " + now.getString("text"));
System.out.println("体感温度: " + now.getString("feelsLike") + "℃");
System.out.println("风速: " + now.getString("windSpeed") + "km/h");
System.out.println("湿度: " + now.getString("humidity") + "%");
} else {
System.out.println("请求失败,状态码:" + response.getStatusLine().getStatusCode());
}
}
}
// 模拟根据城市名获取Location ID(真实场景应调用Geo API)
private static String getLocationId(String city) {
switch (city) {
case "北京": return "101010100";
case "上海": return "101020100";
case "广州": return "101280101";
default: return "101010100"; // 默认北京
}
}}
编译并运行:
javac WeatherApp.java java WeatherApp 北京
输出示例:
城市: 北京基本上就这些。这个项目虽小,但涵盖了网络请求、JSON解析、异常处理等常见技能,适合初学者练手。只要理解流程,后续扩展也不难。关键是先跑通第一个版本。
以上就是在Java中如何开发简易天气查询应用_天气查询项目实践解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号