Android 使用OpenWeatherMapAPI密钥
我得到一个例外。谁能帮我用一下吗。 粘贴以下内容时,可与web浏览器配合使用 我也尝试了以下组合,但没有成功Android 使用OpenWeatherMapAPI密钥,android,weather-api,openweathermap,Android,Weather Api,Openweathermap,我得到一个例外。谁能帮我用一下吗。 粘贴以下内容时,可与web浏览器配合使用 我也尝试了以下组合,但没有成功 connection.addRequestProperty("x-api-key", "&APPID=cea574594b9d36ab688642d5fbeab847e"); private static final String OPEN_WEATHER_MAP_API = "http://api.openweath
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;
}
看来露天天气可能遇到了问题。 我这样说是因为他们给出的示例返回的错误消息与您的相同。 从他们的网站>> API调用示例(没有有效密钥): 试试这个
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();
}
}
class GetData扩展异步任务{
@凌驾
受保护的字符串doInBackground(字符串…参数){
//TODO自动生成的方法存根
字符串结果=”;
HttpURLConnection conn=null;
试一试{
URL=新URL(“http://api.openweathermap.org/data/2.5/weather?q=“+URLEncoder.encode(参数[0],“UTF-8”)+”&APPID=ea574594b9d36ab688642d5fbeab847e”);
conn=(HttpURLConnection)url.openConnection();
InputStream in=新的BufferedInputStream(conn.getInputStream());
if(in!=null){
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(in));
字符串行=”;
而((line=bufferedReader.readLine())!=null)
结果+=行;
}
in.close();
返回结果;
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
最后{
如果(conn!=null)
连接断开();
}
返回结果;
}
@凌驾
受保护的void onPostExecute(字符串结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG.show();
}
}
new Getdata().execute(“您的城市或国家”)代码>
1.-在你的应用程序上添加互联网权限 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();
}
}
公共类MainActivity扩展活动{
JSONObject数据=null;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getJSON(“悉尼”);
}
public void getJSON(最终字符串城市){
新建异步任务(){
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的Void doInBackground(Void…参数){
试一试{
URL=新URL(“http://api.openweathermap.org/data/2.5/weather?q=“+city+”&APPID=ea574594b9d36ab688642d5fbeab847e”);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
缓冲读取器=
新的BufferedReader(新的InputStreamReader(connection.getInputStream());
StringBuffer json=新的StringBuffer(1024);
字符串tmp=“”;
while((tmp=reader.readLine())!=null)
json.append(tmp.append(“\n”);
reader.close();
data=newJSONObject(json.toString());
如果(data.getInt(“cod”)!=200){
系统输出打印项次(“取消”);
返回null;
}
}捕获(例外e){
System.out.println(“异常”+e.getMessage());
返回null;
}
返回null;
}
@凌驾
PostExecute上受保护的void(void void){
如果(数据!=null){
Log.d(“收到我的天气”,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")
}
}
})
val-apiService=
API.getInstance().reformation.create(MyApiEndpointInterface::class.java)
val params=HashMap()
params[“q”]=“英国伦敦”
参数[“APPID”]=“b6907d289e10d714a6e88b30761fae22”
val call=apiService.getUser(参数)
排队(对象:Callback{
覆盖失效时的乐趣(调用:调用?、t:可丢弃?){
Log.e(“错误::”,“错误”+t!!.message)
}
覆盖fun onResponse(调用:调用?,响应:响应?){
if(response!=null&&response.issusccessful&&response.body()!=null){
Log.e(“成功::,“响应”+Response.body()!!.main.temp)
//val tempCel=((response.body()!!.main.temp-32)*5)/9
val tempCel=(response.body()!!.main.temp-273.15f)
温度.setText(${tempCel.roundToInt()}°C”)
}
}
})
你的api密钥应该是一个get参数,而不是x-api-key
应该是什么意思。1111111111不是一个有效的密钥,试试这个CEA5744B9D36AB688642D5FBEAB847E,然后它就可以工作了。很抱歉,开始时有一个额外的“c”,这个可以工作。它只适用于Sydney,它将是静态的,我希望它是动态的,因为我已经添加了编码架构。我已经有了internet权限。我复制并粘贴了你的url,它成功了。非常感谢
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")
}
}
})