我已经继承了代码

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()已@弃用,并显示为“
HttpParams  getParams()
Deprecated.
(4.3) use RequestConfig.

没有RequestConfig的类文档,我不知道应该使用哪种方法来替换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;
}

10-04 23:23
查看更多