Spring Get HttpServletRequest Body Many Times
in developCo-De with 112 comments

Spring Get HttpServletRequest Body Many Times

in developCo-De with 112 comments

Default once consumed, the stram will empty

  public static byte[] getByteBody(HttpServletRequest request) {
    byte[] body = new byte[0];
    try {
      body = StreamUtils.copyToByteArray(request.getInputStream());
    } catch (IOException e) {
      log.error("Error: Get RequestBody byte[] fail," + e);
    }
    return body;
  }

Add Wrapper to Cache stream in byte[]

public class RequestWrapper extends HttpServletRequestWrapper {
  private final byte[] requestBody;
  public RequestWrapper(HttpServletRequest request) {
    super(request);
    requestBody = RequestHelper.getByteBody(request);
  }
  @Override
  public BufferedReader getReader() {
    ServletInputStream inputStream = getInputStream();
    return Objects.isNull(inputStream)
        ? null
        : new BufferedReader(new InputStreamReader(inputStream));
  }
  @Override
  public ServletInputStream getInputStream() {
    if (ObjectUtils.isEmpty(requestBody)) {
      return null;
    }
    final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
    return new ServletInputStream() {
      @Override
      public boolean isFinished() {
        return false;
      }
      @Override
      public boolean isReady() {
        return false;
      }
      @Override
      @SuppressWarnings("EmptyMethod")
      public void setReadListener(ReadListener readListener) {}
      @Override
      public int read() {
        return bais.read();
      }
    };
  }
}

Add Filter wrap the original request

  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    filterChain.doFilter(new RequestWrapper(req), servletResponse);
  }
Comments are closed.