16

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

Xtreme Biker
  • 28,480
  • 12
  • 120
  • 195
tsunade21
  • 3,332
  • 4
  • 23
  • 22
  • 2
    Use `request.getInputStream()` and http://stackoverflow.com/questions/309424/in-java-how-do-a-read-convert-an-inputstream-in-to-a-string – skaffman Apr 26 '11 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? – tsunade21 Apr 27 '11 at 08: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. – James Moore Jul 28 '11 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. – tsunade21 Sep 07 '11 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?" – Michael Jan 05 '14 at 16:25

2 Answers2

17

Using Apache Commons IO:

String requestStr = IOUtils.toString(request.getInputStream());
siledh
  • 3,000
  • 1
  • 14
  • 28
3

Other way, using Guava:

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

See also:

Xtreme Biker
  • 28,480
  • 12
  • 120
  • 195