wang.ramboll.extend.request.limit.wrapper.RequestWrapper Maven / Gradle / Ivy
package wang.ramboll.extend.request.limit.wrapper;
import org.springframework.util.StreamUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
/**
* HttpServletRequest 包装器
* @author WangRuibo
*/
public class RequestWrapper extends HttpServletRequestWrapper {
private byte[] body ;//为解决Request多次读取body问题,冗余一份数据
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
InputStream is = request.getInputStream();
body = StreamUtils.copyToByteArray(is);
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(body)));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return bais.read();
}
};
}
}