尝试通过 JSON 查询从 openweathermap 获取数据时出现 FileNotFoundException

Posted

技术标签:

【中文标题】尝试通过 JSON 查询从 openweathermap 获取数据时出现 FileNotFoundException【英文标题】:Getting FileNotFoundException when trying to get data from openweathermap via JSON query 【发布时间】:2019-07-01 11:20:12 【问题描述】:

我正在 Udacity 课程中构建一个阳光应用程序。在第 2 课中,我尝试将应用程序连接到 OpenWeatherMap.org 网站上的云,以获取城市的天气数据。首先,基本查询有效,即 URL url = 新 URL("http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=c21566b1153f87e9f1d256b962cd6d42"); 但是当我尝试通过 JSON 解析获取数据时,它在 Logcat 中给了我以下错误。

java.io.FileNotFoundException: http://api.openweathermap.org/data/2.5/forecast/daily?q=44000&mode=json&units=metric&cnt=7&APPID=c21566b1153f87e9f1d256b962cd6d42

    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251)
    at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:173)
    at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:110)
    at android.os.AsyncTask$2.call(AsyncTask.java:345)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:257)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:784)##

这是我的代码。

private class FetchWeatherTask extends AsyncTask<String, Void, Void> 

    private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

    @Override
    protected Void doInBackground(String... params) 
        // If there's no zip code, there's nothing to look up.  Verify size     of params.
        if (params.length == 0)
            return null;
        

        // These two need to be declared outside the try/catch
        // so that they can be closed in the finally block.
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        // Will contain the raw JSON response as a string.
        String forecastJsonStr = null;

        String format = "json";
        String units = "metric";
        int numDays = 7;

        try 
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are available at OWM's forecast API page, at
            //
            URL url = new URL("http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=c21566b1153f87e9f1d256b962cd6d42 ");
              //URL url = new URL("http://api.openweathermap.org/data/2.5/weather?zip=94040,us");
                /**Debugging */
            Log.d("Test", "down keycode: " + url);

            final String FORECAST_BASE_URL =
                    "http://api.openweathermap.org/data/2.5/forecast/daily?";
            final String QUERY_PARAM = "q";
            final String FORMAT_PARAM = "mode";
            final String UNITS_PARAM = "units";
            final String DAYS_PARAM = "cnt";
            final String APPID_PARAM = "APPID";

            Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                    .appendQueryParameter(QUERY_PARAM, params[0])
                    .appendQueryParameter(FORMAT_PARAM, format)
                    .appendQueryParameter(UNITS_PARAM, units)
                    .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
                    .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
                    .build();

            url = new URL(builtUri.toString());

            Log.v(LOG_TAG, "Built URI " + builtUri.toString());
            /**Debugging */
            Log.d("Test", "down keycode: " + url);

            //Log.v(LOG_TAG, "Built URI " + builtUri.toString());
            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();



            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) 
                // Nothing to do.
                forecastJsonStr = null;
            
            reader = new BufferedReader(new InputStreamReader(inputStream));



            String line;
            while ((line = reader.readLine()) != null) 
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
                Log.i("Test", String.valueOf(line));

            


            if (buffer.length() == 0) 
                // Stream was empty.  No point in parsing.
                forecastJsonStr = null;
            
            forecastJsonStr = buffer.toString();
         catch (IOException e) 
            Log.e("FetchWeatherTask", "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attempting
            // to parse it.
            Log.d("Test", "Here it reaches", e);
            forecastJsonStr = null;
         finally 
            if (urlConnection != null) 
                urlConnection.disconnect();
            
            if (reader != null) 
                try 
                    reader.close();
                 catch (final IOException e) 
                    Log.e("FetchWeatherTask", "Error closing stream", e);
                
            
        
        return null;
    

JSON解析后构建的url肯定有问题。某些参数肯定是错误的,因为正如我之前所说,上面的基本 url 有效,但是在 JSON 解析之后构建的 url 给出了 filenotfoundexception! 我尝试在互联网上查找此问题,但我的问题无法解决。

这里再次是 JSON 解析之前的 url,它可以从网站获取数据 http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=c21566b1153f87e9f1d256b962cd6d42

这里是在给出 FILENOTFOUNDEXCEPTION 的 JSON 解析之后形成的 url http://api.openweathermap.org/data/2.5/forecast/daily?q=44000&mode=json&units=metric&cnt=7&APPID=c21566b1153f87e9f1d256b962cd6d42

【问题讨论】:

【参考方案1】:

您的问题停留在 q 参数中。对于 OpenWeatherMap api,您必须使用 q 作为参数,后跟 城市名称

api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=xml&units=metric&cnt=7

此处的文档:https://openweathermap.org/forecast16

【讨论】:

以上是关于尝试通过 JSON 查询从 openweathermap 获取数据时出现 FileNotFoundException的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Flutter 中使用 OpenWeather API 的时区属性获取任何城市/国家的当前时间?

OpenWeather API 响应意外结果

尝试通过 JSON 查询从 openweathermap 获取数据时出现 FileNotFoundException

JSON 不可转换为 void (Openweathermap API)

api.openweather

如何从通过 Moya.Response 查询返回的对象解析嵌套的 JSON 数组