Is it possible to read HttpRequest parameters without consuming a stream?

I review the implementation of HiddenMethodFilter in sitebricks here :

Line 65 shows the following code:

try {
    String methodName = httpRequest.getParameter(this.hiddenFieldName);
    if ("POST".equalsIgnoreCase(httpRequest.getMethod()) && !Strings.empty(methodName)) {
    ....

It checks to see if a specific parameter has been set, and uses it to wrap the request. However, when reading this parameter, it will consume the stream, and a possible servlet will not be able to read any data.

What would be the best way to avoid this? I have implemented an HttpServletRequestWrapper here that reads the contents of a stream into an array of bytes. However, it can use a lot of memory to store requests.

private HttpServletRequestWrapper getWrappedRequest(HttpServletRequest httpRequest, final byte[] reqBytes)
   throws IOException {

final ByteArrayInputStream byteInput = new ByteArrayInputStream(reqBytes);
return new HttpServletRequestWrapper(httpRequest) {

  @Override
  public ServletInputStream getInputStream() throws IOException {
    ServletInputStream sis = new ServletInputStream() {

      @Override
      public int read() throws IOException {
        return byteInput.read();
      }
    };
    return sis;
  }
};
}

Is there a better way? Is it possible to read a parameter without consuming a stream? (Something similar to peek) can we reset the stream?

+5
1

POST httpRequest, InputStream, , .
ServletRequest # getParameter javadoc:

, , HTTP POST, getInputStream() getReader() .

ServletInputStream InputStream markSupported reset .., , reset a ServletInputStream.
, .

+2

All Articles