解决SpringBoot v2.2以上重复读取Request Body内容问题

解决SpringBoot v2.2以上重复读取Request Body内容问题

一、需求

项目有两个场景会用到从Request的Body中读取内容。

  1. 打印请求日志
  2. 提供Api接口,在api方法执行前,从Request Body中读取参数进行验签,验签通过后在执行api方法

二、解决方案

2.1 自定义RequestWrapper

public class MyRequestWrapper extends HttpServletRequestWrapper {
	private final String body;

	public MyRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		this.body = RequestReadUtils.read(request);
	}

	public String getBody() {
		return body;
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
		
		return new ServletInputStream() {
			...略
		};
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(this.getInputStream()));
	}

RequestReadUtils(网上抄的)

private static final int BUFFER_SIZE = 1024 * 8;
	 
    public static String read(HttpServletRequest request) throws IOException {
        BufferedReader bufferedReader = request.getReader();
        for (Enumeration<String> iterator = request.getHeaderNames(); iterator.hasMoreElements();) {
        	String type = iterator.nextElement();
			System.out.println(type+" = "+request.getHeader(type));
		}
        System.out.println();
        StringWriter writer = new StringWriter();
        write(bufferedReader,writer);
        return writer.getBuffer().toString();
    }
 
    public static long write(Reader reader,Writer writer) throws IOException {
        return write(reader, writer, BUFFER_SIZE);
    }
 
    public static long write(Reader reader, Writer writer, int bufferSize) throws IOException
    {
        int read;
        long total = 0;
        char[] buf = new char[bufferSize];
        while( ( read = reader.read(buf) ) != -1 ) {
            writer.write(buf, 0, read);
            total += read;
        }
        return total;
    }

2.2 定义Filter

@WebFilter
public class TestFilter implements Filter{
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain){
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		
		MyRequestWrapper wrapper = WebUtils.getNativeRequest(request, MyRequestWrapper.class);
		chain.doFilter(wrapper == null ? new MyRequestWrapper(request) :wrapper,arg1);
	}
}

三、遇到问题

使用的SpringBoot v2.1.x版本

  1. Form提交无问题
  2. 获取RequestBody无问题

使用SpringBoot v2.2.0以上版本(包括v2.3.x)

  1. Form提交 无法获取参数
  2. 获取RequestBody无问题

四、问题排查

经过排查,v2.2.x对比v2.1.x的不同在于一下代码差异:

BufferedReader bufferedReader = request.getReader();
-----------------
char[] buf = new char[bufferSize];
while( ( read = reader.read(buf) ) != -1 ) {
    writer.write(buf, 0, read);
    total += read;
}

当表单提交时

  1. v2.1.x无法read到内容,读取结果为-1
  2. v2.2.x、v2.3.x能够读取到内容

当表单提交时(x-www-form-urlencoded),inputStream读取一次后后续不会触发wrapper的getInputStream操作,所以Controller无法获取到参数。

解决方案

MyRequestWrapper改造

public class MyRequestWrapper extends HttpServletRequestWrapper {

	private final String body;

	public MyRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		this.body = getBodyString(request);
	}

	public String getBody() {
		return body;
	}
	
	public String getBodyString(final HttpServletRequest request) throws IOException {
	    String contentType = request.getContentType();
	    String bodyString = "";
	    StringBuilder sb = new StringBuilder();
	    if (StringUtils.isNotBlank(contentType) && (contentType.contains("multipart/form-data") || contentType.contains("x-www-form-urlencoded"))) {
	        Map<String, String[]> parameterMap = request.getParameterMap();
	        for (Map.Entry<String, String[]> next : parameterMap.entrySet()) {
	            String[] values = next.getValue();
	            String value = null;
	            if (values != null) {
	                if (values.length == 1) {
	                    value = values[0];
	                } else {
	                    value = Arrays.toString(values);
	                }
	            }
	            sb.append(next.getKey()).append("=").append(value).append("&");
	        }
	        if (sb.length() > 0) {
	            bodyString = sb.toString().substring(0, sb.toString().length() - 1);
	        }
	        return bodyString;
	    } else {
	        return IOUtils.toString(request.getInputStream());
	    }
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
		
		return new ServletInputStream() {

			@Override
			public boolean isFinished() {
				return false;
			}

			@Override
			public boolean isReady() {
				return false;
			}

			@Override
			public int read() {
				return bais.read();
			}

			@Override
			public void setReadListener(ReadListener readListener) {

			}
		};
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(this.getInputStream()));
	}

}

原文:https://blog.csdn.net/jlcon/article/details/108520840
作者: jlcon