18

I am trying to get the body of a HttpServletRequest in a String. What's the best elegant way to do so?

5
  • 2
    Use request.getInputStream() and stackoverflow.com/questions/309424/… Commented Apr 26, 2011 at 17:07
  • I wish I could do that @skaffman, however I must read the request body twice. Once to get a json object and the next one to get the string and I always get stream is already closed. Any thoughts? Commented Apr 27, 2011 at 8:23
  • 1
    tsunade21, your comment doesn't make sense. The answer above tells you how to turn your input stream into a string. Needing to read the same stream twice is very likely a bug. Just use the resulting string in both places. Commented Jul 28, 2011 at 22:06
  • 1
    @James Moore, i think i didn't explain myself well before. I had to read the same stream twice because I was using jackson mapping that was reading the stream automatically without giving me any control whatsoever. I finally fixed it, using gson instead of jackson mapping. Commented Sep 7, 2011 at 13:59
  • @JamesMoore is right, reading the stream twice is a bug. You read a Stream from a source you cannot control, from your user's browser. There's simply no way to tell that client "hey, would you send your data once again, please?" Commented Jan 5, 2014 at 16:25

2 Answers 2

19

Using Apache Commons IO:

String requestStr = IOUtils.toString(request.getInputStream());
Sign up to request clarification or add additional context in comments.

Comments

2

Other way, using Guava:

ByteSource.wrap(ByteStreams.toByteArray(request.getInputStream()))
    .asCharSource(Charsets.UTF_8).read()

See also:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.