Skip to content

Instantly share code, notes, and snippets.

@ssawchenko
Created February 28, 2014 23:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssawchenko/9282300 to your computer and use it in GitHub Desktop.
Save ssawchenko/9282300 to your computer and use it in GitHub Desktop.
Helper function which will take an open HttpURLConnection object and read the resulting input stream into a String.
private String TAG = "MyAwesomeApp";
/**
* @param connection object; note: before calling this function, ensure that the connection is already be open,
* and any writes to the connection's output stream should have already been completed.
* @return String containing the body of the connection response or null if the input stream could not be read correctly
*/
private String readHttpInputStreamToString(HttpURLConnection connection) {
String result = null;
StringBuffer sb = new StringBuffer();
InputStream is = null;
try {
is = new BufferedInputStream(connection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
result = sb.toString();
}
catch (Exception e) {
Log.i(TAG, "Error reading InputStream");
result = null;
}
finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
Log.i(TAG, "Error closing InputStream");
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment