com.gitee.apanlh.web.wrapper.RefreshRequestWrapper Maven / Gradle / Ivy
package com.gitee.apanlh.web.wrapper;
import com.gitee.apanlh.util.encode.StrEncodeUtils;
import com.gitee.apanlh.util.io.IOUtils;
import com.gitee.apanlh.web.util.ServletUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
/**
* 重写HttpRequest
*
* @author Pan
*/
public class RefreshRequestWrapper extends HttpServletRequestWrapper {
/** 请求体内容 */
private byte[] requestBody;
/**
* 构造函数-重写HTTPServletRequest请求
*
使用{@link #getBody()}获取请求体内容
*
不会关闭HttpServletRequest中的读取输入流
*
* @author Pan
* @param request HttpServletRequest
*/
public RefreshRequestWrapper(HttpServletRequest request) {
super(request);
this.requestBody = IOUtils.read(ServletUtils.getInputStream(request), false);
}
@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream bais = new ByteArrayInputStream(this.requestBody);
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() {
return bais.read();
}
};
}
@Override
public BufferedReader getReader() {
return IOUtils.getReaderUtf8(getInputStream());
}
/**
* 获取请求体
*
* @author Pan
* @return String
*/
public String getBody() {
return StrEncodeUtils.utf8EncodeToStr(this.requestBody);
}
}