次のコードで公開天気マップapiからJSONデータを取得しようとしていますが、常に失敗します。私は何の例外が発生するのか知りませんし、私は常にキャッチで定義されているようにnull応答を取得します。天気予報地図apiがアンドロイドアプリでデータを返すのはなぜですか?
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;
}
は、ネットワーク状態のアクセス許可を追加する必要がありました...
http://api.openweathermap.org/data/2.5/weather?q=city&units=metricはこれを試してみてくださいBE-必要があります。 –