Apache HttpClient 4.3.5设置代理

时间:2014-08-29 12:07:03

标签: java proxy apache-httpclient-4.x

当我使用:

构造新的HttpClient时,我似乎可以指定代理
HttpHost proxy = new HttpHost("someproxy", 8080);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
    .setRoutePlanner(routePlanner)
    .build();

取自http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e475

是否可以修改现有客户端的代理设置。

1 个答案:

答案 0 :(得分:8)

您可以创建自己的HttpRoutePlanner实现,以允许更改HttpHost。

public class DynamicProxyRoutePlanner implements HttpRoutePlanner {

    private DefaultProxyRoutePlanner defaultProxyRoutePlanner = null;

    public DynamicProxyRoutePlanner(HttpHost host){
        defaultProxyRoutePlanner = new DefaultProxyRoutePlanner(host);
    }

    public void setProxy(HttpHost host){
        defaultProxyRoutePlanner = new DefaultProxyRoutePlanner(host);
    }

    public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) {
        return defaultProxyRoutePlanner.determineRoute(target,request,context); 
    }
}

然后您可以在代码中使用此DynamicProxyRoutePlanner

HttpHost proxy = new HttpHost("someproxy", 8080);
DynamicProxyRoutePlanner routePlanner = new DynamicProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
    .setRoutePlanner(routePlanner)
    .build();

//Any time change the proxy 
routePlanner.setProxy(new HttpHost("someNewProxy", 9090));