我得到了一个异常 "http://api.openweathermap.org/data/2.5/weather?q=Sydney"。请问有人可以帮助如何使用它。当我粘贴以下内容时,在网页浏览器中正常工作:
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;
}
x-api-key
这个意思不明确的参数名。 - njzk2