I am trying to get the body of a HttpServletRequest in a String. What's the best elegant way to do so?
To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.
ServletInputStream class is a component of Java package javax. servlet, It is an abstract class that provides an input stream for reading binary data from a client request, including an efficient readLine method for reading data one line at a time. Syntax: public abstract class ServletInputStream extends InputStream.
Using Apache Commons IO:
String requestStr = IOUtils.toString(request.getInputStream());
Other way, using Guava:
ByteSource.wrap(ByteStreams.toByteArray(request.getInputStream()))
.asCharSource(Charsets.UTF_8).read()
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With