You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何获取REST响应体?求OpenWeather API代码优化建议

优化OpenWeather API调用的Java代码建议

我是第一次在StackOverflow提问的新手开发者,正在尝试实现REST API调用,写了一段用OpenWeather API获取城市温度的代码。我已经尽量让代码整洁了,但还是觉得有些冗余,尤其反感用while循环读取响应体(暂时没找到别的办法),希望各位开发者能给这段代码提些优化建议。

以下是我的代码:

public static void main(String[] args) throws IOException {
    
    Scanner sc = new Scanner(System.in);
    
    while(true) {
        try {
            
            /*
             * 获取用户输入的城市名称
             */
            System.out.print("Enter the city name or enter exit to quit ");
            String cityName = sc.nextLine();
            
            /*
             * 如果用户输入exit,退出循环
             */
            if(cityName.toLowerCase().equals("exit")) {
                System.out.println("exiting...");
                break;
            }
            
            /*
             * 建立连接并发送GET请求
             */
            URL url = new URL("https://api.openweathermap.org/data/2.5/weather?q=" + cityName.toLowerCase() + "&appid=" + Config.API_Key + "&units=metric");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoInput(true);
            connection.connect();
            
            /*
             * 读取响应码,若为200则读取响应体
             */
            int responseCode = connection.getResponseCode();
            if(responseCode == 200) {
                
                String responseBody = "";
                Scanner scanner = new Scanner(url.openStream());
                
                while(scanner.hasNext()) {
                    responseBody += scanner.nextLine();
                }
                
                scanner.close();
                
                
                /*
                 * 解析响应体并提取数据
                 */
                JSONParser parser = new JSONParser();
                JSONObject json = (JSONObject) parser.parse(responseBody);
                
                JSONObject mainObject = (JSONObject) json.get("main");
                
                /*
                 * 获取所需数据并转换为Double类型
                 */
                Double tempInC = ((Number) mainObject.get("temp")).doubleValue();
                Double feelsLike = ((Number) mainObject.get("feels_like")).doubleValue();
                Double temp_min = ((Number) mainObject.get("temp_min")).doubleValue();
                Double temp_max = ((Number) mainObject.get("temp_max")).doubleValue();
                Double pressure = ((Number) mainObject.get("pressure")).doubleValue();
                Double humidity = ((Number) mainObject.get("humidity")).doubleValue();
                
                /*
                 * 输出所有存储的数据
                 */
                System.out.println("The current temperature for " + cityName + " is " + tempInC + " C");
                System.out.println("It feels like " + feelsLike + " C" + " in " + cityName);
                System.out.println("The minimum temperature for " + cityName + " is " + temp_min + " C");
                System.out.println("The maximum temperature for " + cityName + " is " + temp_max + " C");
                System.out.println("The air pressure for " + cityName + " is " + pressure + " kPa");
                System.out.println("The humidity level for " + cityName + " is " + humidity + " gm^3");
                
                System.out.println();
                
            }
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

运行输出

Enter the city name or enter exit to quit Toronto
The current temperature for Toronto is 18.63 C
It feels like 18.56 C in Toronto
The minimum temperature for Toronto is 17.49 C
The maximum temperature for Toronto is 20.06 C
The air pressure for Toronto is 1017.0 kPa
The humidity level for Toronto is 77.0 gm^3

Enter the city name or enter exit to quit Dallas
The current temperature for Dallas is 27.61 C
It feels like 29.6 C in Dallas
The minimum temperature for Dallas is 25.52 C
The maximum temperature for Dallas is 29.32 C
The air pressure for Dallas is 1017.0 kPa
The humidity level for Dallas is 67.0 gm^3

Enter the city name or enter exit to quit Paris
The current temperature for Paris is 19.94 C
It feels like 19.58 C in Paris
The minimum temperature for Paris is 16.34 C
The maximum temperature for Paris is 21.19 C
The air pressure for Paris is 1022.0 kPa
The humidity level for Paris is 61.0 gm^3

Enter the city name or enter exit to quit exit
exiting...

响应体示例

{
    "coord": {
    "lon": -79.4163,
    "lat": 43.7001
},
"weather": [
    {
        "id": 803,
        "main": "Clouds",
        "description": "broken clouds",
        "icon": "04n"
    }
],
"base": "stations",
"main": {
    "temp": 18.84,
    "feels_like": 18.76,
    "temp_min": 17.83,
    "temp_max": 20.06,
    "pressure": 1017,
    "humidity": 76
},
"visibility": 10000,
"wind": {
    "speed": 4.12,
    "deg": 70
},
"clouds": {
    "all": 75
},
"dt": 1660101834,
"sys": {
    "type": 1,
    "id": 718,
    "country": "CA",
    "sunrise": 1660040128,
    "sunset": 1660091458
},
"timezone": -14400,
"id": 6167865,
"name": "Toronto",
"cod": 200
}

内容的提问来源于stack exchange,提问作者Mehsum Naqvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:30:56