使用SpringBoot WebClient时如何拦截请求 [英] How to intercept a request when using SpringBoot WebClient

查看:54
本文介绍了使用SpringBoot WebClient时如何拦截请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 WebClient 来调用我的 restServices.之前在 RestTemplate 上,我们定义了 ClientHttpRequestInterceptor 并将其附加到 RestTemplate 以拦截和修改请求.使用 WebClient,有没有办法做同样的事情?

I am trying to use the WebClient to call my restServices. Previously on RestTemplate, we had ClientHttpRequestInterceptor defined and attached to the RestTemplate to intercept and modify the requests. With the WebClient, is there a way to do the same ?

谢谢,

-Sreeni

推荐答案

当您使用 WebClient Builder 时,您可以使用 filter() 传入 ExchangeFilterFunction 接口的实现代码>方法.这相当于 `RestTemplate.

When you are using the WebClient Builder you can pass in implementations of the ExchangeFilterFunction interface using the filter() method. This is the equivalent of the ClientHttpRequestInterceptor for `RestTemplate.

WebClient Builder 文档:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.Builder.html#filter-org.springframework.web.reactive.function.client.ExchangeFilterFunction-

WebClient Builder Docs: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.Builder.html#filter-org.springframework.web.reactive.function.client.ExchangeFilterFunction-

ExchangeFilterFunction 文档:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/ExchangeFilterFunction.html

ExchangeFilterFunction Docs: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/ExchangeFilterFunction.html

例如:

WebClient webClient = WebClient.builder()
        .baseUrl("http://localhost:8080|)
        .filter(logFilter())
        .build();


private ExchangeFilterFunction logFilter() {
    return (clientRequest, next) -> {
        logger.info("External Request to {}", clientRequest.url());
        return next.exchange(clientRequest);
    };
}

这篇关于使用SpringBoot WebClient时如何拦截请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆