Получение FileNotFoundException при попытке получить данные из openweathermap через JSON-запрос - PullRequest
0 голосов
/ 07 февраля 2019

Я создаю солнечное приложение из курса 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;
    }

Определенно существует проблема с URL, который создается послеРазбор JSON.Некоторый параметр, который должен быть неверным, потому что, как я сказал ранее, базовый URL выше работает, но URL, созданный после анализа JSON, дает исключение filenotfoundexception!Я попытался просмотреть эту проблему через Интернет, но моя проблема не была решена.

Здесь снова URL-адрес перед анализом JSON, который работает и получает данные с веб-сайта http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=c21566b1153f87e9f1d256b962cd6d42

и здесь URLкоторый формируется после анализа JSON, который дает FILENOTFOUNDEXCEPTION http://api.openweathermap.org/data/2.5/forecast/daily?q=44000&mode=json&units=metric&cnt=7&APPID=c21566b1153f87e9f1d256b962cd6d42

1 Ответ

0 голосов
/ 07 февраля 2019

Ваша проблема остается в параметре q.Для API OpenWeatherMap вы должны использовать q в качестве параметра, за которым следует название города .

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

Документация здесь: https://openweathermap.org/forecast16

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...