我正在尝试使用以下代码从打开的天气地图 api 中获取 JSON 数据,但它总是失败。我不知道发生了什么异常,我总是得到捕获中定义的空响应。
try {
//URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
URL url = new URL(String.format(OPEN_WEATHER_MAP_API));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key",
context.getString(R.string.open_weather_maps_app_id));
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}
return data;
}catch(Exception e){
return null;
}