TIL: Enabling Proxy in Spring WebClient

If you are trying to setup webclient in spring boot you may came across following code snippet

import org.springframework.context.annotation.Bean;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.transport.ProxyProvider;

@Component
public class WebClientConfig {

    @Bean
    public WebClient proxiedWebClient() {
        HttpClient httpClient = HttpClient.create()
            .proxy(proxy -> proxy
                .type(ProxyProvider.Proxy.HTTP)
                .host("localhost")
                .port(8500)
            );

        return WebClient.builder()
            .clientConnector(new ReactorClientHttpConnector(httpClient))
            .build();
    }
}

As of today, that approach doesn’t seem to function, the workaround was to switch to Apache HttpClient 5.

Import statements

implementation 'org.apache.httpcomponents.client5:httpclient5'
implementation 'org.apache.httpcomponents.core5:httpcore5-reactive'
@Bean
public WebClient authenticationWebClient() {

  if (!proxyEnabled) {
    return WebClient.builder().build();
  }

  HttpHost proxy = new HttpHost(proxyHost, proxyPort);

  CloseableHttpAsyncClient asyncClient =
      HttpAsyncClients.custom().setProxy(proxy).build();

  asyncClient.start();

  return WebClient.builder()
      .clientConnector(new HttpComponentsClientHttpConnector(asyncClient))
      .build();
}

If your Netty-based WebClient proxy setup isn’t behaving as expected, try falling back to Apache’s implementation. It’s just works.

Related Post