Skip to content

Instantly share code, notes, and snippets.

@wuapnjie
Last active March 5, 2016 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wuapnjie/01ad86f6cf448157d2e3 to your computer and use it in GitHub Desktop.
Save wuapnjie/01ad86f6cf448157d2e3 to your computer and use it in GitHub Desktop.
Normal network connection
try {
URL url = new URL("<api call>");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
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) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
result = buffer.toString();
} catch (IOException e) {
Log.e("Request", "Error ", e);
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("Request", "Error closing stream", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment