package com.iailab.module.data.framework.filter;
|
|
import groovy.util.logging.Slf4j;
|
import lombok.Getter;
|
|
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;
|
import java.io.IOException;
|
import java.io.InputStreamReader;
|
|
@Slf4j
|
@Getter
|
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
|
/** 复制请求body */
|
private final String body;
|
|
public MyHttpServletRequestWrapper (HttpServletRequest request) {
|
super(request);
|
try {
|
//设置编码格式, 防止中文乱码
|
request.setCharacterEncoding("UTF-8");
|
//将请求中的流取出来放到body里,后面都只操作body就行
|
this.body = RequestReadUtils.read(request);
|
} catch (Exception e) {
|
throw new RuntimeException("MyHttpServletRequestWrapper 拦截器异常");
|
}
|
}
|
|
@Override
|
public ServletInputStream getInputStream() {
|
//返回body的流信息即可
|
try(final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes())){
|
return getServletInputStream(bais);
|
}catch(IOException e){
|
throw new RuntimeException("MyHttpServletRequestWrapper 获取input流异常");
|
}
|
}
|
|
@Override
|
public BufferedReader getReader(){
|
return new BufferedReader(new InputStreamReader(this.getInputStream()));
|
}
|
|
/**
|
* 重写getInputStream流
|
* @param bais
|
* @return
|
*/
|
private static ServletInputStream getServletInputStream(ByteArrayInputStream bais) {
|
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();
|
}
|
};
|
}
|
}
|