通过 HttpClient 的 Spring Boot 代理不起作用

问题描述 投票:0回答:2

我正在尝试使用代理在 Spring 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 调用后,我收到“连接超时:无更多信息”。我应该返回一个 Bad Request(以防我的调用错误),但我没有。

执行有误吗? proxyName 是这样写的:“proxy.blabla.de”

spring-boot proxy httpclient
2个回答
0
投票

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

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

0
投票

当您使用

create()
方法创建新的 HttpClient 时,它不会为它返回构建器,而是 实际的客户端 以及其他设置它的方法,如
proxy
followRedirect
等等实际上是这个HttpClient的返回clones

所以你要么必须使用“构建器”链方法,或者重写你的变量,然后再将它传递给

WebClient.Builder.clientConnector()
方法

像这样:

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.