httpClient.getConnectionManager() 已弃用-应该改用啥?
Posted
技术标签:
【中文标题】httpClient.getConnectionManager() 已弃用-应该改用啥?【英文标题】:httpClient.getConnectionManager() is deprecated - what should be used instead?httpClient.getConnectionManager() 已弃用-应该改用什么? 【发布时间】:2014-01-09 21:19:05 【问题描述】:我继承了代码
import org.apache.http.client.HttpClient;
...
HttpClient httpclient = createHttpClientOrProxy();
try
HttpPost postRequest = postRequest(data, url);
body = readResponseIntoBody(body, httpclient, postRequest);
catch( IOException ioe )
throw new RuntimeException("Cannot post/read", ioe);
finally
httpclient.getConnectionManager().shutdown(); // ** Deprecated
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")) )
log.warn("http.proxyHost = " + System.getProperty("http.proxyHost") );
log.warn("http.proxyPort = " + System.getProperty("http.proxyPort"));
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;
getConnectionManager()
读作“
@Deprecated
ClientConnectionManager getConnectionManager()
Deprecated. (4.3) use HttpClientBuilder.
Obtains the connection manager used by this client.
HttpClientBuilder 的文档似乎很少,简单地说:
Builder for CloseableHttpClient instances.
但是,如果我将 HttpClient
替换为 CloseableHttpClient
,则该方法似乎仍然是 @Deprecated
。
如何使用非弃用方法?
【问题讨论】:
你想做什么?获取ClientConnectionManager
?为什么?
你能发布更多代码吗?就像httpClient
的初始化方式一样。
我已经发布了用于创建 HttpClient 的代码。我无法回答“为什么”,因为我没有编写原始代码。
你能解释一下吗? httpclient.getConnectionManager().shutdown();。我为 HttpClientBuilder 创建了对象 httpclient = HttpClientBuilder.create();我们如何修改与httpclient 4.3.3 jar相关的
未弃用:developer.android.com/reference/org/apache/http/client/…
【参考方案1】:
不要创建 HttpClient
的新实例,而是使用 Builder。你会得到一个CloseableHttpClient
。
例如用法:
CloseableHttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build()
不要使用getConnectionManager().shutdown()
,而是在CloseableHttpClient
上使用close()
方法。
【讨论】:
以上是关于httpClient.getConnectionManager() 已弃用-应该改用啥?的主要内容,如果未能解决你的问题,请参考以下文章