2013-12-21 147 views
16

我繼承的代碼如何用RequestConfig替換棄用的httpClient.getParams()?

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

回答

8

您正在使用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; 
} 
12

這更多的是後續的@Stephane Lallemagne

沒有給出答案爲使HttpClient的拾取系統代理設置

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

或本得多的conciser方式,如果你想要的HttpClient的與系統解完全配置實例故障

CloseableHttpClient client = HttpClients.createSystem(); 
+0

謝謝;奧列格我只是重用你的答案[這裏](http://stackoverflow.com/questions/10297837/set-nonproxyhosts-in-apache-httpclient-4-1-3/32653727#32653727) – boly38

相關問題