gpt4 book ai didi

java - 如何将 ServerHttpRequest/ServerHttpResponse 主体转换为字符串

转载 作者:行者123 更新时间:2023-12-02 07:38:14 33 4
gpt4 key购买 nike

想要在 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 中解释的方法在这种情况下, map 函数不会随时执行。

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

没有任何效果......

有什么想法或可能的方法来解决这个“获取 body ”问题吗?

最佳答案

只需创建另一个过滤器并记录所有请求、响应。

    @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);
}

}

关于java - 如何将 ServerHttpRequest/ServerHttpResponse 主体转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54189144/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com