IllegalStateException: getInputStream() has already been called for this request

10,806

Solution 1

Looks like the restlet framework has called getRequestEntityStream() on the Request object which in turn calls getInputStream(), so calling getReader() on the request throws IllegalStateException.

The Servlet API documentation for getReader() and getInputStream() says:

 public java.io.BufferedReader getReader()
    ...
    ...
Throws:
    java.lang.IllegalStateException - if getInputStream() method has been called on this request

 public ServletInputStream getInputStream()
    ...
    ...
    Throws:
    java.lang.IllegalStateException - if the getReader() method has already been called for this request

From the documentation it seems that I cannot call both getReader() and getInputStream() on the Request object (even though it wasn't me that was doing it).

I had to instead use getInputStream() rather than getReader().

Solution 2

It is illegal to write to both servletRequest.getReader() and servletRequest.getInputStream(). I think servletRequest.getInputStream() was also called before which is leading to IllegalStateException.

Share:
10,806
Garvice
Author by

Garvice

Updated on June 29, 2022

Comments

  • Garvice
    Garvice almost 2 years

    Getting an illegal state exception when I try to get the Buffered Reader from the HttpServletResponse telling me that getInputStream has already been called. However getReader is the first line of code, and I'm not calling getInputStream at all...

    Server:

    @POST
    @Path("/getReport")
    @Produces(MediaType.TEXT_HTML)
    @Consumes(MediaType.APPLICATION_JSON)
    public void getReport(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse, @Context UriInfo uriInfo )
                throws ServletException, IOException{
    
    JSONObject jobj =  new JSONObject(new JSONTokener(servletRequest.getReader()));
    
  • Garvice
    Garvice about 12 years
    ummm How is it getting called? I am not calling getInputStream() and getReader() is my first line.
  • Ramesh PVK
    Ramesh PVK about 12 years
    Can you check any of your filters is calling. If you want to debug Implement a RequestWrapper and add debug in getInputStream().