Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform ServletInputStream to String

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

like image 395
tsunade21 Avatar asked Apr 26 '11 16:04

tsunade21


People also ask

How to convert InputStream to String?

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.

What is Java ServletInputStream?

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.


2 Answers

Using Apache Commons IO:

String requestStr = IOUtils.toString(request.getInputStream());
like image 143
siledh Avatar answered Oct 23 '22 13:10

siledh


Other way, using Guava:

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

See also:

  • http://www.baeldung.com/java-convert-inputstream-to-reader
like image 30
Xtreme Biker Avatar answered Oct 23 '22 13:10

Xtreme Biker