gpt4 book ai didi

android - 使用 OpenWeatherMap API key

转载 作者:太空狗 更新时间:2023-10-29 15:31:11 24 4
gpt4 key购买 nike

我得到异常“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;
}

最佳答案

1.-在您的应用上添加互联网权限 How to add manifest permission to android application?

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();

}
}

enter image description here

关于android - 使用 OpenWeatherMap API key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34321728/

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