使用 OpenWeatherMap API 键
Using OpenWeatherMap API Key
我得到异常“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;
}
Open Weather 似乎遇到了问题。
我这样说是因为他们给出的示例返回的错误消息与您的相同。
从他们的网站 >>
http://openweathermap.org/appid
API 调用示例(没有有效密钥):
api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=1111111111
试试这个
创建一个 class 名为 GetData
class GetData extends AsyncTask <String,Void,String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String result = "";
HttpURLConnection conn = null;
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q="+URLEncoder.encode(params[0], "UTF-8")+"&APPID=ea574594b9d36ab688642d5fbeab847e");
conn = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(conn.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
return result;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if(conn!=null)
conn.disconnect();
}
return result;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
然后用这个获取数据
new Getdata().execute("your city or country");
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();
}
}
改造后的工作示例
val apiService =
API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
val params = HashMap<String, String>()
params["q"] = "London,uk"
params["APPID"] = "b6907d289e10d714a6e88b30761fae22"
val call = apiService.getUser(params)
call.enqueue(object : Callback<WeatherResponse> {
override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
Log.e("Error:::","Error "+t!!.message)
}
override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
if (response != null && response.isSuccessful && response.body() != null) {
Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)
// val tempCel = ((response.body()!!.main.temp - 32)*5)/9
val tempCel = (response.body()!!.main.temp - 273.15f)
temperature.setText("${tempCel.roundToInt()}°C")
}
}
})
我得到异常“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;
}
Open Weather 似乎遇到了问题。 我这样说是因为他们给出的示例返回的错误消息与您的相同。 从他们的网站 >> http://openweathermap.org/appid
API 调用示例(没有有效密钥):
api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=1111111111
试试这个
创建一个 class 名为 GetData
class GetData extends AsyncTask <String,Void,String> { @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub String result = ""; HttpURLConnection conn = null; try { URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q="+URLEncoder.encode(params[0], "UTF-8")+"&APPID=ea574594b9d36ab688642d5fbeab847e"); conn = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(conn.getInputStream()); if (in != null) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = bufferedReader.readLine()) != null) result += line; } in.close(); return result; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(conn!=null) conn.disconnect(); } return result; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show(); } }
然后用这个获取数据
new Getdata().execute("your city or country");
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();
}
}
改造后的工作示例
val apiService =
API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
val params = HashMap<String, String>()
params["q"] = "London,uk"
params["APPID"] = "b6907d289e10d714a6e88b30761fae22"
val call = apiService.getUser(params)
call.enqueue(object : Callback<WeatherResponse> {
override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
Log.e("Error:::","Error "+t!!.message)
}
override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
if (response != null && response.isSuccessful && response.body() != null) {
Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)
// val tempCel = ((response.body()!!.main.temp - 32)*5)/9
val tempCel = (response.body()!!.main.temp - 273.15f)
temperature.setText("${tempCel.roundToInt()}°C")
}
}
})