Default once consumed, the stram will empty
public static byte[] getByteBody(HttpServletRequest request) {
byte[] body = new byte[0];
try {
body = StreamUtils.copyToByteArray(request.getInputStream());
} catch (IOException e) {
log.error("Error: Get RequestBody byte[] fail," + e);
}
return body;
}
Add Wrapper to Cache stream in byte[]
public class RequestWrapper extends HttpServletRequestWrapper {
private final byte[] requestBody;
public RequestWrapper(HttpServletRequest request) {
super(request);
requestBody = RequestHelper.getByteBody(request);
}
@Override
public BufferedReader getReader() {
ServletInputStream inputStream = getInputStream();
return Objects.isNull(inputStream)
? null
: new BufferedReader(new InputStreamReader(inputStream));
}
@Override
public ServletInputStream getInputStream() {
if (ObjectUtils.isEmpty(requestBody)) {
return null;
}
final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
@SuppressWarnings("EmptyMethod")
public void setReadListener(ReadListener readListener) {}
@Override
public int read() {
return bais.read();
}
};
}
}
Add Filter wrap the original request
public void doFilter(
ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
filterChain.doFilter(new RequestWrapper(req), servletResponse);
}
本文由 Ivan Dong 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Jul 7, 2023 at 04:09 am