多次读取Request数据流

1.需要多次读取Request中携带的数据流,但是默认的只能读取一次;

2.如果需要多次读取Request中携带的数据流,需要重写 HttpServletRequestWrapper 的getReader() 和 getInputStream()方法;

3.代码:


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class InputStreamReadRepeatableRequestWrapper extends HttpServletRequestWrapper {
	
	private final byte[] body; // 报文

	public InputStreamReadRepeatableRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		body = InputStreamToByte(request.getInputStream());
	}
	
	/**
	 * 流转 字节数组 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private byte[] InputStreamToByte(InputStream is) throws IOException {
	   ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
	   byte[] buffer=new byte[1024];
	   int ch;
	   while ((ch = is.read(buffer)) != -1) {
		   bytestream.write(buffer,0,ch);
	   }
	   byte data[] = bytestream.toByteArray();
	   bytestream.close();
	   return data;
	 }
	
	@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 int read() throws IOException {
				return bais.read();
			}
		};
	}

}

 

你可能感兴趣的:(服务器相关)