I'm calling a BufferedReader to get a HTTP response body (if it exists) and stick it in one long string variable. Sometimes when I attempt to do this I get the error java.io.IOException: stream is closed sometimes when the while loop below starts to execute. I don't understand why. I'd like to make sure the object isn't null and that is has a response body before reading in the object.
BufferedReader readBuffer = null;
if (connection.getResponseCode() >= 200 && connection.getResponseCode() <= 299) {
readBuffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
readBuffer = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
if(readBuffer != null) {
// Get the response body output from the server
StringBuilder calculatedOutput = new StringBuilder();
String rawOutputLine;
while ((rawOutputLine = readBuffer.readLine()) != null) {
calculatedOutput.append(rawOutputLine);
}
Logger.debug(String.format("BODY: %s", calculatedOutput.toString()));
readBuffer.close();