BufferedReader java.io.IOException: stream is closed

时间:2018-03-09 19:08:09

标签: java stream bufferedreader

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();

2 个答案:

答案 0 :(得分:1)

请尝试阅读回复:

    BufferedReader readBuffer = null;

    try {
        if (connection.getResponseCode() >= 200 && connection.getResponseCode() <= 299) {
            readBuffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            readBuffer = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }
        // 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()));
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            readBuffer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

答案 1 :(得分:0)

尝试以下代码:

for unq_date in R_Unique_Dates: