Request body二次取得的问题

  • Post author:
  • Post category:其他



HttpServletRequest中的取得body的方法有两种:getInputStream()、getReader()。


但是这个两个方法只能用一次,取第二次的时候就会变为null,然而

HttpServletRequest中的body二进制还是有的,感觉特别奇怪,

原因可能是游标的变动,

HttpServletRequest第一次取body时游标以跑到二进制流的尾部,然后第二次去的时候就取不到了,解决方法如下:







重写HttpServletRequestWrapper







public class BodyReaderHttpServletRequestWrapper extends



HttpServletRequestWrapper {



private byte[] body;



public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) {




super(request);



String charset = request.getCharacterEncoding();



if (StringUtils.isNullOrEmpty(charset)) {




charset = “utf-8”;



}



try {




body = StreamUtil.readBytes(request.getReader(), charset);



} catch (IOException e) {




e.printStackTrace();



}



}



@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();



}



@Override



public boolean isFinished() {




return false;



}



@Override



public boolean isReady() {




return false;



}



@Override



public void setReadListener(ReadListener readListener) {







}



};



}




然后  ServletRequest requestWrapper


= new BodyReaderHttpServletRequestWrapper((HttpServletRequest);







之后用

requestWrapper就可随便去body值了。








版权声明:本文为huangjinlong77原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。