如何获取ServerHttpRequest / ServerHttpResponse正文到字符串

时间:2019-01-14 21:03:20

标签: java spring

想在Spring API Gateway之上实现代理以记录请求/响应。 我为传入请求和传出响应定义了自己的过滤器。

请求网关过滤器:

public class RequestGatewayFilter extends AbstractGatewayFilterFactory<RequestGatewayFilter.Config> {

private static final Logger logger = LogManager.getLogger(RequestGatewayFilter.class);

public RequestGatewayFilter() {
    super(Config.class);
}

@Autowired
CustomProxyLogger customLogger;

@Override
public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
        ServerHttpRequest.Builder builder = exchange.getRequest().mutate()
                .header(PR_CORRELATION_ID, UUID.randomUUID().toString());
        ServerHttpRequest request = builder.build();
        customLogger.logRequest(logger, request);
        return chain.filter(exchange.mutate().request(request).build());
    };
}

}

响应网关过滤器:

public class ResponseGatewayFilter extends AbstractGatewayFilterFactory<ResponseGatewayFilter.Config> {

private static final Logger logger = LogManager.getLogger(ResponseGatewayFilter.class);

public ResponseGatewayFilter() {
    super(Config.class);
}

@Autowired
CustomProxyLogger customLogger;

@Override
public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            ServerHttpResponse response = exchange.getResponse();
            customLogger.logResponse(logger, exchange);
        }));
    };
}

我必须记录请求和响应正文。我尝试了几种方法,例如How to correctly read Flux<DataBuffer> and convert it to a single inputStream中所述 在这种情况下,地图函数无法随时执行。

还尝试将ServerHttpRequest强制转换为HttpServletRequest以便从那里获取主体,但这会引发Cast Exception。

没有工作。...

解决这个“弄死身体”问题的想法或可行方法?

1 个答案:

答案 0 :(得分:-1)

只需创建另一个Filter并记录所有请求和响应。

    @Component
    public class RequestResponseLoggingFilter implements Filter {

...

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            LOG.info(request);
            chain.doFilter(request, response);
            LOG.info(response);
        }

    }