答案:开发Java天气查询工具需调用OpenWeatherMap等API,通过HttpURLConnection获取数据并用org.json解析,结合命令行或Swing界面展示结果。1. 注册API密钥并构造请求URL;2. 使用HttpURLConnection发送GET请求,读取JSON响应;3. 解析城市、温度、天气描述等字段并输出;4. 可选Swing构建图形界面提升交互体验。

开发一个天气查询小工具在Java中并不复杂,核心思路是调用第三方天气API获取数据,并通过简单的界面或命令行展示结果。下面从准备到实现一步步说明如何完成这个小工具。
目前有许多免费的天气API可以使用,比如:
以 OpenWeatherMap 为例,注册账号后进入控制台获取你的 API Key,例如:your_api_key_here。
使用它的当前天气接口地址为:
http://api.openweathermap.org/data/2.5/weather?q=城市名&appid=你的密钥&units=metric&lang=zh_cn
其中 units=metric 表示温度单位为摄氏度,lang=zh_cn 支持中文描述。
Java原生可以使用 java.net.HttpURLConnection 发起HTTP请求,再用 JSON 解析库处理返回结果。推荐使用 org.json 库简化操作。
立即学习“Java免费学习笔记(深入)”;
先添加依赖(如果使用Maven):
<font color="gray">
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230618</version>
</dependency>
</font>核心代码示例:
<font color="gray">
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherTool {
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 static void getWeather(String city) {
try {
String urlString = BASE_URL + "?q=" + city + "&appid=" + API_KEY + "&units=metric&lang=zh_cn";
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();
// 解析JSON
JSONObject json = new JSONObject(response.toString());
String cityName = json.getString("name");
double temp = json.getJSONObject("main").getDouble("temp");
String description = json.getJSONArray("weather").getJSONObject(0).getString("description");
System.out.println("城市: " + cityName);
System.out.println("温度: " + temp + "°C");
System.out.println("天气: " + description);
} catch (Exception e) {
System.out.println("无法获取天气信息,请检查城市名称或网络连接。");
e.printStackTrace();
}
}
}
</font>写一个 main 方法让用户输入城市名查询天气:
<font color="gray">
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入城市名称: ");
String city = scanner.nextLine();
WeatherTool.getWeather(city);
}
}
</font>运行程序,输入“Beijing”或“上海”,即可看到类似输出:
<font color="blue"> 城市: 上海 温度: 22.3°C 天气: 多云 </font>
如果想让工具更友好,可以用 Swing 做个简单界面:
<font color="gray">
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WeatherGUI extends JFrame {
private JTextField cityField;
private JButton queryButton;
private JLabel resultLabel;
public WeatherGUI() {
setTitle("天气查询小工具");
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
cityField = new JTextField(15);
queryButton = new JButton("查询");
resultLabel = new JLabel("请输入城市名称...");
queryButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String city = cityField.getText();
if (!city.isEmpty()) {
// 重定向输出到resultLabel(实际中可改进为返回字符串)
// 这里简化处理,直接调用并显示
// 更佳做法是修改getWeather返回字符串
resultLabel.setText("");
new Thread(() -> {
String result = fetchWeather(city);
resultLabel.setText("<html>" + result.replace("\n", "<br>") + "</html>");
}).start();
}
}
});
JPanel panel = new JPanel();
panel.add(new JLabel("城市: "));
panel.add(cityField);
panel.add(queryButton);
panel.add(resultLabel);
add(panel);
}
// 简化版返回字符串结果
private String fetchWeather(String city) {
try {
// (此处复用上面的请求逻辑,封装成返回字符串)
// 为了简洁,省略重复代码,实际应提取共用方法
} catch (Exception e) {
return "查询失败:" + e.getMessage();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new WeatherGUI().setVisible(true);
});
}
}
</font>基本上就这些。通过调用API、处理HTTP请求和解析JSON,你就能用Java做出一个实用的天气查询工具。后续还可以扩展功能,比如支持定位、天气预报、图标显示等。
以上就是Java中如何开发一个天气查询小工具的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号