我正在关注 Tutplus 和 youtube 关于 Android WeatherApp 创建的教程。请在下面找到我的代码。我正在尝试连接到 OpenWeatherMap 并获取 JSON 天气数据。这是我的问题:
- 它不工作。
- 这是创建访问 OpenWeatherMap 的 URL 的正确方法吗?
- 当我注册 OpenWeatherMap 时,它给了我一个 KEY。我不知道该怎么办。在从服务器获取 httpurlconnection 以设置“x-api-key”之后,我在我的代码中使用了它。不知道它是否需要或正在做
- 当我得到输入流时,阅读器为空,然后应用程序挂起。
这是代码:
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
}