1

I'm new to Spring Cloud Gateway (spring boot 2.0.5.RELEASE). I try to read the request body from a web filter and the request is just stuck and cannot flow through the chain. Sample code:

@Component
public class TestFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(TestFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        try {
            /* whenever I put the following line. The request cannot get through */
            ByteBuffer byteBuffer = Mono.from(serverHttpRequest.getBody()).toFuture().get().asByteBuffer();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return chain.filter(exchange);
    }
}

If I remove the getBody() line, everything works fine. Any clue? Thx!

Rick Lee
  • 743
  • 2
  • 7
  • 19
  • You can only read the body once after that it has been consumed and cannot be read again. You will have to create a wrapper which makes it possible to read the body multiple times (just like a classic servlet filter wrapping a `HttpServletRequest` and copying all read bytes to a `byte[]` so it can be read again). – M. Deinum Jan 11 '19 at 10:47

1 Answers1

0

Have a look here: How can I read request body multiple times in Spring 'HandlerMethodArgumentResolver'?

This remark explains it pretty accurate:

The biggest problem is that I find out that HttpServletRequest(get from NativeWebRequest) cannot read input stream(some parameters are in the request body) more than one time