Skip to content

Instantly share code, notes, and snippets.

@robocide
Forked from KamilLelonek/weather.java
Last active August 29, 2015 14:06
Show Gist options
  • Save robocide/98ec31e95d99fd965655 to your computer and use it in GitHub Desktop.
Save robocide/98ec31e95d99fd965655 to your computer and use it in GitHub Desktop.
Android: Consuming Web service
HttpUrlconnection connection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
connection = (HttpUrlconnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
StringBuilder builder = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
forecastJsonStr = builder.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment