title: How to safely log request body from HttpServletRequest without interferring main logic?
body: <p>In my Web service app I have the request object which is an instance of HttpServletRequest. The problem is some client(customer) is sending some invalid request in the body and I want to log it. In my logging class I have the reference to the request object, but using the function below I got a "StreamClosed" exception. I think it is because Jackson has already consumed the stream and closed it in its json deserialization process. </p>
  
  <p>So my question is, how do I safely log the request body in case it is invalid? Apparently I cannot log it up-front before the Jackson tries to deserialize it because that would tamper the input stream. </p>
  
  <pre><code>        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)) &gt; 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;
  }
  </code></pre>