How to intercept a request when using SpringBoot WebClient

后端 未结 3 587
广开言路
广开言路 2020-12-18 10:26

I am trying to use the WebClient to call my restServices. Previously on RestTemplate, we had ClientHttpRequestInterceptor defined and

3条回答
  •  时光取名叫无心
    2020-12-18 11:27

    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 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 Docs: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/ExchangeFilterFunction.html

    For example:

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

提交回复
热议问题