Java 不推荐使用 httpClient.getConnectionManager() - 应该使用什么代替?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20713321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
httpClient.getConnectionManager() is deprecated - what should be used instead?
提问by peter.murray.rust
I have inherited the code
我继承了代码
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()
reads "
getConnectionManager()
读“
@Deprecated
ClientConnectionManager getConnectionManager()
Deprecated. (4.3) use HttpClientBuilder.
Obtains the connection manager used by this client.
The docs for HttpClientBuilder seem sparse and simply say:
HttpClientBuilder 的文档似乎很少,只是说:
Builder for CloseableHttpClient instances.
However if I replace HttpClient
with CloseableHttpClient
the method still seems @Deprecated
.
但是,如果我HttpClient
用CloseableHttpClient
该方法替换似乎仍然存在@Deprecated
。
How can I use a non-Deprecated method?
如何使用未弃用的方法?
采纳答案by SiN
Instead of creating a new instance of HttpClient
, use the Builder. You would get a CloseableHttpClient
.
不要创建 的新实例,而是HttpClient
使用 Builder。你会得到一个CloseableHttpClient
.
e.g usage:
例如用法:
CloseableHttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build()
Instead of using getConnectionManager().shutdown()
, use the close()
method instead on CloseableHttpClient
.
不要使用getConnectionManager().shutdown()
,而是使用close()
方法 on CloseableHttpClient
。