【问题标题】:Why dont open weather map api return data in android app?为什么不在 Android 应用中打开天气地图 API 返回数据?
【发布时间】:2016-05-31 11:53:47
【问题描述】:

我正在尝试使用以下代码从打开的天气地图 api 中获取 JSON 数据,但它总是失败。我不知道发生了什么异常,我总是得到捕获中定义的空响应。

 try {
        //URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
        URL url = new URL(String.format(OPEN_WEATHER_MAP_API));
        HttpURLConnection connection =
                (HttpURLConnection)url.openConnection();

        connection.addRequestProperty("x-api-key",
                context.getString(R.string.open_weather_maps_app_id));

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));

        StringBuffer json = new StringBuffer(1024);
        String tmp="";
        while((tmp=reader.readLine())!=null)
            json.append(tmp).append("\n");
        reader.close();

        JSONObject data = new JSONObject(json.toString());

        // This value will be 404 if the request was not
        // successful
        if(data.getInt("cod") != 200){
            return null;
        }

        return data;
    }catch(Exception e){
        return null;
    }

【问题讨论】:

    标签: android json rest openweathermap


    【解决方案1】:

    如果不知道您是如何创建 URL 的,您似乎在 String.format 中错过了这座城市

    URL url = new URL(String.format(OPEN_WEATHER_MAP_API));
    

    不应该

    URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
    

    【讨论】:

      【解决方案2】:

      我在这里发表评论,因为我无权在您的问题线程中发表评论。 打印您的 catch 块的堆栈跟踪,您也许能够找到解决问题的方法。

      【讨论】:

        【解决方案3】:

        我必须添加以下权限以及互联网权限。

        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        

        【讨论】:

          【解决方案4】:

          您为您的 OPEN_WEATHER_MAP_API..分配了什么 URL?

          网址应该是-http://api.openweathermap.org/data/2.5/weather?q=city&units=metric

          请试试这个...

          【讨论】:

            猜你喜欢
            • 2018-09-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-12-30
            相关资源
            最近更新 更多