如何将已弃用的 httpClient.getParams() 替换为 RequestConfig?

2022-09-02 21:27:56

我继承了代码

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()@Deprecated并读取”

HttpParams  getParams()
Deprecated. 
(4.3) use RequestConfig.

RequestConfig没有类文档,我不知道应该使用什么方法来替换和。getParams()ConnRoutePNames.DEFAULT_PROXY


答案 1

这更像是@Stephane Lallemagne给出的答案的后续。

有一种更简洁的方法可以使HttpClient拾取系统代理设置

CloseableHttpClient client = HttpClients.custom()
        .setRoutePlanner(
             new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
        .build();

或者,如果您希望使用系统默认值完全配置 HttpClient 的实例,则可以这样做

CloseableHttpClient client = HttpClients.createSystem();

答案 2

您正在将 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;
}

推荐