I get Exception "http://api.openweathermap.org/data/2.5/weather?q=Sydney". Can someone please help how to use it. Works fine with the web browser when i paste the following
http://api.openweathermap.org/data/2.5/weather?q=Sydney&APPID=ea574594b9d36ab688642d5fbeab847e
I tried the following combination as well but no luck
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.-Add internet permission on your app How to add manifest permission to android application?
2.-Here you have an example about how implement an api call
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With