Skip to content

Instantly share code, notes, and snippets.

@mminer
Created August 21, 2019 17:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mminer/35065abfa44f9b45833d5c8c00ec62b1 to your computer and use it in GitHub Desktop.
Save mminer/35065abfa44f9b45833d5c8c00ec62b1 to your computer and use it in GitHub Desktop.
Servlet request wrapper that allows reading request body multiple times.
package com.matthewminer;
import org.apache.commons.io.IOUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private byte[] cache;
public MultiReadHttpServletRequest(HttpServletRequest request) {
super(request);
try {
ServletInputStream inputStream = super.getInputStream();
cache = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
cache = new byte[0];
}
}
@Override
public ServletInputStream getInputStream() {
ByteArrayInputStream inputStream = new ByteArrayInputStream(cache);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return inputStream.available() == 0;
}
@Override
public boolean isReady() {
return true;
}
@Override
public int read() {
return inputStream.read();
}
@Override
public void setReadListener(ReadListener readListener) {
throw new UnsupportedOperationException();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment