title: How to retrieve raw post data from HttpServletRequest in java
body: <p>I'm trying to get the post data in Java. Seems like it should be one of the simplest things to do right? I mean, HttpServletRequest.getParameter has to do it right? So how can you get the raw post data?</p>
  
  <p>I found <a href="https://stackoverflow.com/questions/3831680/httpservletrequest-get-post-data">HttpServletRequest get JSON POST data</a> and used Kdeveloper's code to pull the post data from a request. It works, but theres a catch: I can only get that post data <em>once</em>.</p>
  
  <p>Heres the method I made from Kdeveloper's code:</p>
  
  <pre><code>public static String getPostData(HttpServletRequest req) {
      StringBuilder sb = new StringBuilder();
      try {
          BufferedReader reader = req.getReader();
          reader.mark(10000);
  
          String line;
          do {
              line = reader.readLine();
              sb.append(line).append("\n");
          } while (line != null);
          reader.reset();
          // do NOT close the reader here, or you won't be able to get the post data twice
      } catch(IOException e) {
          logger.warn("getPostData couldn't.. get the post data", e);  // This has happened if the request's reader is closed    
      }
  
      return sb.toString();
  }
  </code></pre>
  
  <p>Previously I had closed the reader at the end of this method, but that caused exceptions when the method ran more than once on the same request. Without closing it, no exceptions happen, but the method returns an empty string.</p>
  
  <p>Honestly, there should just be an exposed req.getPostData() method - did no one think that would be useful?</p>
  
  <p>So how can I write this method such that it always returns the correct post data?</p>