当前位置: 首页 > 知识库问答 >
问题:

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

刘安志
2023-03-14

我正在建立一个阳光应用从Udacity课程。在第2课中,我尝试将应用程序连接到OpenWeatherMap.org站点上的云,以获取城市的天气数据。首先,基本查询起作用,即URL URL=新URL(“http://api.openweathermap.org/data/2.5/forecast?id=524901&appid=c21566b1153f87e9f1d256b962cd6d42”);但当我试图通过JSON解析获取数据时,它在logcat中给出以下错误。

    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

这里是JSON解析后形成的url,它给出FILENOTFOUNDEXCEPTION http://api.openweathermap.org/data/2.5/forection/daily?q=44000&mode=JSON&units=metric&cnt=7&appid=c21566b1153f87e9f1d256b962cd6d42

共有1个答案

郎华皓
2023-03-14

问题出在q参数上。对于OpenWeatherMap api,您必须使用q作为参数,后跟城市名。

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

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

 类似资料:
  • 问题内容: 当我尝试获取我的keyChain值时,它返回一个包含以下内容的字符串: 因此,我尝试使用循环删除“可选”: 但我得到一个错误:NSString没有名为“下标”的成员 KeychainService类: 我只是不想删除str周围的Optional东西,还是有更好的方法呢? 我从以下代码中获取了代码: http://matthewpalmer.net/blog/2014/06/21/exa

  • 尝试从本地文件获取 json 数据并继续获取 “JSON.parse:数据意外结束在第 1 行第 1 列” 。 我已经尝试了fetch函数的许多参数,但是我总是得到至少一个错误。 JSON数据 我想安慰你。记录数据以确保其正常运行。

  • 我想通过“id”从我的mongodb获取数据。如果我的id与mongodb中id的值匹配,则它将获取该对象,但其抛出错误为: {“message”:“对于模型“PostMessage”“”的路径“\u id”处的值“s-CoAhDKd”,转换为ObjectId失败}

  • 我正在创建一个android应用程序,它以json格式显示从在线API获取的天气数据。为此,我使用的是格森图书馆。 我有以下JSON字符串,我从一个map对象中获得: 它包含以下值: 但是,当我尝试使用该字符串创建另一个贴图对象时,我遇到了一个异常。 异常logcat报告: 通用域名格式。谷歌。格森。JsonSyntaxException:com。谷歌。格森。流动MalformedJsonExce

  • //回收器和视图 //调用提取数据方法extractData(); //提取数据

  • 我想得到openweathermap图标。https://openweathermap.org/weather-conditions和http://samples.openweathermap.org/data/2.5/weather?q=London,英国 非常感谢你。你的建议对我很重要