Apache HTTP 客户端和代理的条件设置

Apache HTTP Client and conditional setting of proxy

我正在使用以下代码实例化 Apache HTTP 组件 HttpClient:

CloseableHttpClient httpClient = HttpClients.custom()
        .setProxy(new HttpHost(proxyServerAddress, proxyServerPort))
        .disableConnectionState()
        .disableCookieManagement()
        .build();

但我只想在 属性(例如 useProxy)设置为 true 时设置代理。我可以使用基于 属性 值的 if-then-else 对块,但我想知道是否有更好的方法来实现这一点?我的目标是使用配置文件 属性 或通过 JAVA_OPTS.

外部化是否使用代理的控制

怎么样:

HttpClientBuilder builder = HttpClients.custom()
        .disableConnectionState()
        .disableCookieManagement();

if( useProxy )
    builder = builder.setProxy(new HttpHost(proxyServerAddress, proxyServerPort));

CloseableHttpClient httpClient = builder.build();