我使用以下代码实例化Apache HTTP Components HttpClient:
CloseableHttpClient httpClient = HttpClients.custom()
.setProxy(new HttpHost(proxyServerAddress, proxyServerPort))
.disableConnectionState()
.disableCookieManagement()
.build();
但我想仅在属性(例如useProxy
)设置为true
时才设置代理。我可以根据属性值使用if-then-else
块对,但我想知道是否有更好的方法来实现这一点?我的目标是使用配置文件属性或通过JAVA_OPTS
外部控制是否使用代理。
答案 0 :(得分:1)
怎么样:
HttpClientBuilder builder = HttpClients.custom()
.disableConnectionState()
.disableCookieManagement();
if( useProxy )
builder = builder.setProxy(new HttpHost(proxyServerAddress, proxyServerPort));
CloseableHttpClient httpClient = builder.build();