我得到例外"http://api.openweathermap.org/data/2.5/weather?q=Sydney“。有人能帮忙如何使用它吗。粘贴以下内容时,web浏览器可以正常工作
http://api.openweathermap.org/data/2.5/weather?q=Sydney&APPID=ea574594b9d36ab688642d5fbeab847e
我也尝试了下面的组合,但是没有运气。
connection.addRequestProperty("x-api-key",
"&APPID=cea574594b9d36ab688642d5fbeab847e");
private static final String OPEN_WEATHER_MAP_API =
"http://api.openweathermap.org/data/2.5/weather?q=%s";
public static JSONObject getJSON(String city) {
try {
URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key",
"cea574594b9d36ab688642d5fbeab847e");
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());
if(data.getInt("cod") != 200) {
System.out.println("Cancelled");
return null;
}
return data;
} catch (Exception e) {
System.out.println("Exception "+ e.getMessage());
return null;
} 发布于 2015-12-16 21:27:56
1.-在应用程序How to add manifest permission to android application?上添加internet权限
2.-这里有一个如何实现api调用的示例
public class MainActivity extends Activity {
JSONObject data = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getJSON("Sydney");
}
public void getJSON(final String city) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q="+city+"&APPID=ea574594b9d36ab688642d5fbeab847e");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
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();
data = new JSONObject(json.toString());
if(data.getInt("cod") != 200) {
System.out.println("Cancelled");
return null;
}
} catch (Exception e) {
System.out.println("Exception "+ e.getMessage());
return null;
}
return null;
}
@Override
protected void onPostExecute(Void Void) {
if(data!=null){
Log.d("my weather received",data.toString());
}
}
}.execute();
}
}

发布于 2015-12-16 20:54:18
看来开放天气可能遇到了问题。我这么说是因为他们给出的例子是返回与您相同的错误消息。从他们的网站>> http://openweathermap.org/appid
API调用示例(没有有效密钥):
api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=1111111111发布于 2015-12-16 20:55:33
尝尝这个
new Getdata().execute("your city or country");https://stackoverflow.com/questions/34321728
复制相似问题