我继承了代码
import org.apache.http.client.HttpClient;
...
HttpClient httpclient = createHttpClientOrProxy();
...
private HttpClient createHttpClientOrProxy() {
HttpClient httpclient = new DefaultHttpClient();
/*
* Set an HTTP proxy if it is specified in system properties.
*
* http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
* http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientExecuteProxy.java
*/
if( isSet(System.getProperty("http.proxyHost")) ) {
int port = 80;
if( isSet(System.getProperty("http.proxyPort")) ) {
port = Integer.parseInt(System.getProperty("http.proxyPort"));
}
HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"), port, "http");
// @Deprecated methods here... getParams() and ConnRoutePNames
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
return httpclient;
}
httpClient.getParams()
是@Deprecated,读为“
HttpParams getParams()
Deprecated.
(4.3) use RequestConfig.
RequestConfig没有类文档,我不知道应该使用什么方法来替换getParams()
和ConnRoutePNames.DEFAULT_PROXY
。
答案 0 :(得分:13)
这更像是@Stephane Lallemagne给出答案的后续行动
有一种非常简洁的方法可以让HttpClient获取系统代理设置
CloseableHttpClient client = HttpClients.custom()
.setRoutePlanner(
new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
.build();
或者如果你想要一个HttpClient实例完全配置系统默认值
CloseableHttpClient client = HttpClients.createSystem();
答案 1 :(得分:10)
你正在使用带有apache HttpClient 4.2代码的apache HttpClient 4.3库。
请注意,getParams()和ConnRoutePNames不是您的案例中唯一不推荐使用的方法。 DefaultHttpClient类本身依赖于4.2实现,也在4.3中弃用。
关于这里的4.3文档(http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/connmgmt.html#d5e473),你可以这样重写:
private HttpClient createHttpClientOrProxy() {
HttpClientBuilder hcBuilder = HttpClients.custom();
// Set HTTP proxy, if specified in system properties
if( isSet(System.getProperty("http.proxyHost")) ) {
int port = 80;
if( isSet(System.getProperty("http.proxyPort")) ) {
port = Integer.parseInt(System.getProperty("http.proxyPort"));
}
HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"), port, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
hcBuilder.setRoutePlanner(routePlanner);
}
CloseableHttpClient httpClient = hcBuilder.build();
return httpClient;
}