不推荐使用httpClient.getConnectionManager() - 应该使用什么?

时间:2013-12-20 23:04:48

标签: java apache http

我继承了代码

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

如何使用非弃用方法?

1 个答案:

答案 0 :(得分:35)

使用Builder,而不是创建HttpClient的新实例。你会得到一个CloseableHttpClient。

例如用法:

CloseableHttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build()

而不是使用getConnectionManager()。shutdown(),而是在CloseableHttpClient上使用close()方法。