为什么不在 android 应用程序中打开天气图 api return 数据?
Why dont open weather map api return data in android app?
我正在尝试使用以下代码从开放天气图 api 中获取 JSON 数据,但总是失败。我不知道发生了什么异常,我总是得到 catch 中定义的空响应。
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;
}
我在这里发表评论是因为我没有特权在您的问题线程中发表评论。
打印 catch 块的堆栈跟踪,您也许可以找到解决问题的方法。
不知道你是如何创建你的 URL,你似乎错过了你 String.format
中的城市
URL url = new URL(String.format(OPEN_WEATHER_MAP_API));
不应该吗
URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
我必须添加以下权限以及互联网权限。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
您为 OPEN_WEATHER_MAP_API..分配了什么 URL?
url 应该是- http://api.openweathermap.org/data/2.5/weather?q=city&units=metric
请试试这个...
我正在尝试使用以下代码从开放天气图 api 中获取 JSON 数据,但总是失败。我不知道发生了什么异常,我总是得到 catch 中定义的空响应。
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;
}
我在这里发表评论是因为我没有特权在您的问题线程中发表评论。 打印 catch 块的堆栈跟踪,您也许可以找到解决问题的方法。
不知道你是如何创建你的 URL,你似乎错过了你 String.format
URL url = new URL(String.format(OPEN_WEATHER_MAP_API));
不应该吗
URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
我必须添加以下权限以及互联网权限。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
您为 OPEN_WEATHER_MAP_API..分配了什么 URL?
url 应该是- http://api.openweathermap.org/data/2.5/weather?q=city&units=metric
请试试这个...