如何使用HandlerInterceptorAdapter修改HttpServletRequest方法中的请求主体

时间:2018-12-06 16:18:24

标签: java spring spring-mvc spring-boot

我尝试使用HttpRequestWrapper,但是它一直给我流关闭的异常。以下是我的HttpRequestWrapper代码。我试图在preHandle方法中修改请求正文。修改请求主体后,我想将其发送到控制器。好像HandlerInterceptorAdapter被调用了两次。第二次,它抱怨流关闭。我已经看到了与此问题相关的帖子,但找不到解决方案。

public class RequestWrapper extends HttpServletRequestWrapper {
private final String body;
public RequestWrapper(HttpServletRequest request) throws IOException {
    super(request);
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;
    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } else {
            stringBuilder.append("");
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw ex;
            }
        }
    }
    body = stringBuilder.toString();
}

@Override
public ServletInputStream getInputStream() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new     ByteArrayInputStream(body.getBytes());
    ServletInputStream servletInputStream = new ServletInputStream() {
        @Override public boolean isFinished() {
            return false;
        }

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

        @Override public void setReadListener(ReadListener readListener) {

        }

        public int read() throws IOException {
            return byteArrayInputStream.read();
        }
    };
    return servletInputStream;
}

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

public String getBody() {
    return this.body;
}

}

0 个答案:

没有答案