Spring Boot 通过HttpClient的Sping Boot Proxy不工作

jhiyze9q  于 2023-05-22  发布在  Spring
关注(0)|答案(2)|浏览(229)

我正在尝试使用代理在Sping Boot 中设置WebClient连接。我的实现如下所示:

final WebClient.Builder webclientBuilder = WebClient.builder();

final HttpClient httpClient = HttpClient.create();
httpClient.proxy(proxy -> proxy
                    .type(Proxy.HTTP)
                    .host(proxyName)
                    .port(Integer.parseInt(proxyPort)));

    final ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
    webclientBuilder.clientConnector(connector);

final WebClient webClient = webclientBuilder
        .baseUrl(baseUrl)
        .build();

运行它并发送API调用后,我收到“Connection timeout:无进一步信息”。我应该得到一个错误的请求(如果我的电话是错误的),但我没有。
执行是否错误?proxyName是这样写的:“proxy.blabla.de“

guicsvcw

guicsvcw1#

经过反复试验和比较,我找到了一个适合我的解决方案:

String baseUrl = "https://mybaseurl";
String proxyName = "proxy.blabla.de";
int proxyPort = 1234;

public InitResponse addAccount() {

    //  for logging purposes, nothing to do with the proxy
    LOGGER.info("LOGGER.info: addAccount()");
    final InitRequest request = buildRequest();

    HttpClient httpClient = HttpClient.create()
                    .proxy(proxy -> proxy.type(Proxy.HTTP)
                    .host(proxyName)
                    .port(proxyPort));

    ReactorClientHttpConnector conn = new ReactorClientHttpConnector(httpClient);
    WebClient webClient = WebClient.builder().clientConnector(conn).baseUrl(baseUrl).build();
w80xi6nr

w80xi6nr2#

当你使用create()方法创建新的HttpClient时,它不会返回builder,而是返回实际的客户端而其他设置它的方法,如proxyfollowRedirect等,实际上是返回这个HttpClient的克隆
因此,您必须使用“构建器”链方法,在将变量传递给WebClient.Builder.clientConnector()方法之前重写变量**
就像这样:

HttpClient httpClient = HttpClient.create().
    followRedirect(true);

// this is crucial
httpClient = httpClient.responseTimeout(Duration.ofSeconds(60));

作者从未试图解释HttpClient不工作背后的实际原因是什么...

相关问题