0

I am trying to read raw data from a post request body, I am using the code below to do this task, When trying to read the body I get "Stream Closed" exception, I have also tried to use "getReader()" function and got the same error, what am I missing here?

public static String getBody(HttpServletRequest request) throws IOException {

String body = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;

try {
    InputStream inputStream = request.getInputStream();
    if (inputStream != null) {
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        char[] charBuffer = new char[128];
        int bytesRead = -1;
        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
            stringBuilder.append(charBuffer, 0, bytesRead);
        }
    } else {
        stringBuilder.append("");
    }
} catch (IOException ex) {
    throw ex;
} finally {
    if (bufferedReader != null) {
        try {
            bufferedReader.close();
        } catch (IOException ex) {
            throw ex;
        }
    }
}

body = stringBuilder.toString();
return body;

}

0 Answers0