我使用以下代码实例化 Apache HTTP 组件 HttpClient:
CloseableHttpClient httpClient = HttpClients.custom()
.setProxy(new HttpHost(proxyServerAddress, proxyServerPort))
.disableConnectionState()
.disableCookieManagement()
.build();
但我只想在属性(例如 useProxy
)设置为 true
时设置代理。我可以根据属性值使用 if-then-else 对 block ,但我想知道是否有更好的方法来实现这一点?我的目标是使用配置文件属性或通过 JAVA_OPTS
来外部化是否使用代理的控制。
最佳答案
怎么样:
HttpClientBuilder builder = HttpClients.custom()
.disableConnectionState()
.disableCookieManagement();
if( useProxy )
builder = builder.setProxy(new HttpHost(proxyServerAddress, proxyServerPort));
CloseableHttpClient httpClient = builder.build();
关于java - Apache HTTP Client 和代理的条件设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41818016/