0

我正在关注 Tutplus 和 youtube 关于 Android WeatherApp 创建的教程。请在下面找到我的代码。我正在尝试连接到 OpenWeatherMap 并获取 JSON 天气数据。这是我的问题:

  1. 它不工作。
  2. 这是创建访问 OpenWeatherMap 的 URL 的正确方法吗?
  3. 当我注册 OpenWeatherMap 时,它给了我一个 KEY。我不知道该怎么办。在从服务器获取 httpurlconnection 以设置“x-api-key”之后,我在我的代码中使用了它。不知道它是否需要或正在做
  4. 当我得到输入流时,阅读器为空,然后应用程序挂起。

这是代码:

public class WeatherGrabber {

private static final String TAG = "WeatherGrabber";

private static final String CURRENT_WEATHER_URL = 
"http://api.openweathermap.org/data/2.5/weather?q=%s&mode=json";

private static BufferedReader reader;
private static final String my_key = "307ec986e69c22c9a24a1bcf9edd21ea";


public static String loadCurrentWeather(Context context, String city) {

    String data = null;

    try{

      URL web_url = new URL(String.format(CURRENT_WEATHER_URL, city) );

      HttpURLConnection conn = (HttpURLConnection) 
                               web_url.openConnection();
        conn.addRequestProperty("x-api-key", my_key);


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

            String inputLine;

            StringBuffer json = new StringBuffer();

            while((inputLine = reader.readLine() )!= null){

                json.append(inputLine).append("\n");

            }
            data = json.toString();



    }catch (IOException e){
        e.printStackTrace();
    }finally {
        try {
            if (in != null)
                in.close();
        }catch (Exception e) {
            e.printStackTrace();

        }
    }
    return data;
}// end of loadCurrentWeather() method


}
4

1 回答 1

0
  1. 您不能直接在主线程上运行网络请求。您需要使用 AsyncTask 类来执行此操作。

在您的活动中创建课程

private class LoadCurrentWeatherAsync extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... params) {

        try {
            //Call to your function here
            return loadCurrentWeather(MainActivity.this, "newyork");
        } catch (Exception e){
            return e.toString();
        }

    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        //Do what ever you what with this output
        Log.d("data", s);

    }

}

然后在您的活动 onCreate 方法中调用它

new LoadCurrentWeatherAsync().execute();

还要确保您已在 AndroidManifest.xml 中启用互联网权限。在清单标签内插入

<uses-permission android:name="android.permission.INTERNET" />
  1. 没关系

  2. 他们使用 api 密钥来跟踪请求是来自免费计划还是付费计划。

  3. 我怀疑那是因为您在主线程上发送网络请求。试试上面的代码

于 2015-09-16T08:58:03.550 回答