I am trying to get the body of a HttpServletRequest in a String. What's the best elegant way to do so?
Asked
Active
Viewed 1.9k times
16
-
2Use `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
-
1tsunade21, 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 Answers
17
Using Apache Commons IO:
String requestStr = IOUtils.toString(request.getInputStream());
![](../../users/profiles/1121633.webp)
siledh
- 3,000
- 1
- 14
- 28
3
Other way, using Guava:
ByteSource.wrap(ByteStreams.toByteArray(request.getInputStream()))
.asCharSource(Charsets.UTF_8).read()
See also:
![](../../users/profiles/1199132.webp)
Xtreme Biker
- 28,480
- 12
- 120
- 195