Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

java - httpClient.getConnectionManager() is deprecated - what should be used instead?

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 "

@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:

Builder for CloseableHttpClient instances.

However if I replace HttpClient with CloseableHttpClient the method still seems @Deprecated.

How can I use a non-Deprecated method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of creating a new instance of HttpClient, use the Builder. You would get a CloseableHttpClient.

e.g usage:

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

Instead of using getConnectionManager().shutdown(), use the close() method instead on CloseableHttpClient.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...