Web Services JavaSpring:如何从ClientResponse访问原始请求?

mlmc2os5  于 2023-01-26  发布在  Java
关注(0)|答案(1)|浏览(130)

背景
ClientResponse最有可能在内部访问原始请求,如createError()等方法的文档所示:
创建一个以WebClientResponseException结尾的Mono,其中包含响应状态、头、主体和原始请求

问题

是否有办法访问来自ClientResponse的原始请求?

背后的动机

我正在使用ExchangeFilterFunction.ofResponseProcessor()编写我自己的ExchangeFilterFunction,我还想在其中访问 * 原始请求:

@Bean
public ExchangeFilterFunction logResponse() {
    return ExchangeFilterFunction.ofResponseProcessor(response -> {
        return Mono.just(response)
            .doOnEach(resp -> log.info("""
                        {} {}
                        {}
                        Response Headers: {}""",
                ORIG_METHOD, ORIG_URI, // Here I need the originating request
                response.statusCode(),
                response.headers().asHttpHeaders())
            );
    });
}
yqkkidmi

yqkkidmi1#

不确定是否可以从ClientResponse访问ClientRequest,
但您可以使用ExchangeFilterFunction同时访问这两个文件
ExchangeFilterFunction是一个@FunctionalInterface,这意味着我们可以使用简单的lambda来完成此任务

@Bean
public ExchangeFilterFunction logResponse() {
    return (request, next) -> {
    // here you have access to request object
        return next.exchange(request)
                   .doOnEach(response -> {/*here you have access to request AND response objects*/});
    };
}

此外,您还将使用Mono.doOnEach,它将Consumer〈Signal〉作为参数
我建议切换到Mono.doOnNext以访问ClientResponse而不是Signal
因此,您的示例(不带括号)如下所示:

@Bean
public ExchangeFilterFunction logResponse() {
    return (request, next) -> 
        next.exchange(request)
            .doOnNext(response -> 
                log.info("""
                    {} {}
                    {}
                    Response Headers: {}""",
                request.method(), 
                request.url,
                response.statusCode(),
                response.headers().asHttpHeaders()));

相关问题