Java中如何开发一个天气查询小工具

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

java中如何开发一个天气查询小工具

开发一个天气查询小工具在Java中并不复杂,核心思路是调用第三方天气API获取数据,并通过简单的界面或命令行展示结果。下面从准备到实现一步步说明如何完成这个小工具。

1. 选择天气API并获取密钥

目前有许多免费的天气API可以使用,比如:

OpenWeatherMap(https://openweathermap.org/api):提供当前天气、预报、地理编码等接口,注册后可获得免费API Key。 和风天气(https://dev.qweather.com):中文支持好,适合国内用户。

以 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 支持中文描述。

2. 使用HttpURLConnection发送请求并解析JSON

Java原生可以使用 java.net.HttpURLConnection 发起HTTP请求,再用 JSON 解析库处理返回结果。推荐使用 org.json 库简化操作。

立即学习“Java免费学习笔记(深入)”;

先添加依赖(如果使用Maven):

    org.json    json    20230618

核心代码示例:

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();        }    }}

3. 添加主方法进行测试

写一个 main 方法让用户输入城市名查询天气:

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);    }}

运行程序,输入“Beijing”或“上海”,即可看到类似输出:

城市: 上海温度: 22.3°C天气: 多云

4. 可选:增加图形界面(Swing)

如果想让工具更友好,可以用 Swing 做个简单界面:

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("" + result.replace("n", "
") + ""); }).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); }); }}

基本上就这些。通过调用API、处理HTTP请求和解析JSON,你就能用Java做出一个实用的天气查询工具。后续还可以扩展功能,比如支持定位、天气预报、图标显示等。

以上就是Java中如何开发一个天气查询小工具的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/77502.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月14日 21:59:36
下一篇 2025年11月14日 22:30:16

相关推荐

发表回复

登录后才能评论
关注微信