Created
February 28, 2014 23:42
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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