request中inputStream多次读取

原创

在使用HTTP协议实现应用间接口通信时,服务端读取客户端请求过来的数据,会用到request.getInputStream(),第一次读取的时候可以读取到数据,但是接下来的读取操作都读取不到数据。

原因:

  1. 一个InputStream对象在被读取完成后,将无法被再次读取,始终返回-1;
  2. InputStream并没有实现reset方法(可以重置首次读取的位置),无法实现重置操作;

解决方法(缓存读取到的数据):

  1. 使用request、session等来缓存读取到的数据,这种方式很容易实现,只要setAttribute和getAttribute就行;
  2. 使用HttpServletRequestWrapper来包装HttpServletRequest,在中初始化读取request的InputStream数据,以byte[]形式缓存在其中,然后在Filter中将request转换为包装过的request;

代码

  1. 编写rHttpServletRequestWrapper子类,用来处理请求数据

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Enumeration;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper
{
   

	private final byte[] body;

	public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException
	{
   
		super(request);
		Enumeration<String> e = request.getHeaderNames();
		while (e.hasMoreElements())
		{
   
			String name = (String) e.nextElement();
			String value = request.getHeader(name);
			log.debug("HttpServletRequest头信息:{}-{}", name, value);
		}
		body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
	}

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

	@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 listener)
			{
   
				
			}

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

	@Override
	public String getHeader(String name)
	{
   
		return super.getHeader(name);
	}

	@Override
	public Enumeration<String> getHeaderNames()
	{
   
		return super.getHeaderNames();
	}

	@Override
	public Enumeration<String> getHeaders(String name)
	{
   
		return super.getHeaders(name);
	}

}

2.调用

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
	{
   
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		ServletRequest requestWrapper = null;
		requestWrapper = new BodyReaderHttpServletRequestWrapper(httpRequest);
		
		//数据读取处理
		//...
		//将requestWrapper专递给后面的过滤器
		filterChain.doFilter(requestWrapper, httpResponse);
	}
正文到此结束