如何用RequestConfig替换不推荐使用的httpClient.getParams()?
我inheritance了代码
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.
ConnRoutePNames.DEFAULT_PROXY
没有类文档,我不知道应该用什么方法来替换getParams()
和ConnRoutePNames.DEFAULT_PROXY
。
您正在使用apache HttpClient 4.3库与apache HttpClient 4.2代码。
请注意,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; }
这更像是@Stephane Lallemagne给出的答案的后续行动
有一种非常简洁的方法可以让HttpClient获取系统代理设置
CloseableHttpClient client = HttpClients.custom() .setRoutePlanner( new SystemDefaultRoutePlanner(ProxySelector.getDefault())) .build();
或者,如果您希望HttpClient实例完全配置系统默认值
CloseableHttpClient client = HttpClients.createSystem();