Skip to content

Instantly share code, notes, and snippets.

@naanT
Created August 20, 2015 21:49
Show Gist options
  • Save naanT/a44de61fb6e7c4953610 to your computer and use it in GitHub Desktop.
Save naanT/a44de61fb6e7c4953610 to your computer and use it in GitHub Desktop.
HttpURLConnection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment