解决spring boot处理request.getInputStream()输入流只能读取一次问题

正常普通接口请求,request.getParameter()可以获取,能多次读取

如果我们的接口是用@RequestBody来接受数据,那么我们在拦截器中

需要读取request的输入流  ,因为 ServletRequest中getReader()和getInputStream()只能调用一次

这样就会导致controller 无法拿到数据。

解决方法 :

1、自定义一个类 BodyReaderHttpServletRequestWrapper.java 

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

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

import org.springframework.util.StreamUtils;

/**
 * @author WBG
 * @date 2020/6/22 10:42
 * @describe
 */
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper{

    private byte[] requestBody = null;//用于将流保存下来

    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        requestBody = StreamUtils.copyToByteArray(request.getInputStream());

    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);

        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) {

            }
        };
    }

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

2、自定义 MyFilter  继承Filter

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author WBG
 * @date 2020/6/22 14:32
 * @describe
 */
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("开始");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper=null;
        if(request instanceof HttpServletRequest) {
            requestWrapper=new BodyReaderHttpServletRequestWrapper((HttpServletRequest)request);
        }
        if(requestWrapper==null) {
            chain.doFilter(request, response);
        }else {
            System.out.println("------------------------------请求报文----------------------------------");
            System.out.println(getParamsFromRequestBody((HttpServletRequest) requestWrapper));
            System.out.println("------------------------------请求报文----------------------------------");
            chain.doFilter(requestWrapper, response);
        }

    }
    /* *
     * 获取请求体内容
     * @return
     * @throws IOException
     */

    private String getParamsFromRequestBody(HttpServletRequest request) throws IOException {
        BufferedReader br = null;
        String listString = "";
        try {
            br = request.getReader();

            String str = "";

            while ((str = br.readLine()) != null) {
                listString += str;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return listString;
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
    }
}

3、配置过滤器

 
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
 
/**
 * 解决request请求无法连续打开InputStream问题
 * @author huangan
 * @date 2020/11/19 22:56
 */
 
@Slf4j
@WebFilter(urlPatterns = "/*",filterName = "channelFilter")
public class HttpServletRequestReplacedFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        log.info(".............................. 进入过滤器 ..............................");
        if(servletRequest instanceof HttpServletRequest){
            requestWrapper = new BodyReaderRequestWrapper((HttpServletRequest)servletRequest);
        }
        if(null == requestWrapper){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            filterChain.doFilter(requestWrapper,servletResponse);
        }
    }
 
    @Override
    public void destroy() {
    }
}

4.配置@ServletComponentScan扫描过滤器

  • 0
    点赞
  • 0
    评论
  • 2
    收藏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值