gpt4 book ai didi

android - 为什么不在android应用中打开weather map api返回数据?

转载 作者:行者123 更新时间:2023-11-29 19:46:29 30 4
gpt4 key购买 nike

我正在尝试使用以下代码从开放天气图 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;
}

最佳答案

不知道您是如何创建 URL 的,看起来您在 String.format

中缺少城市
URL url = new URL(String.format(OPEN_WEATHER_MAP_API));

不应该吗

URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));

关于android - 为什么不在android应用中打开weather map api返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37545047/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com