Apache HTTP Client和代理的条件设置

时间:2017-01-24 00:22:25

标签: java apache-httpclient-4.x

我使用以下代码实例化Apache HTTP Components HttpClient:

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

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

1 个答案:

答案 0 :(得分:1)

怎么样:

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

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

CloseableHttpClient httpClient = builder.build();