Apache HttpClient 4.3.5 set proxy

旧街凉风 提交于 2019-11-29 01:15:33

问题


It seems that I can specify the proxy when I construct new HttpClient with:

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

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

Is it possible to modify existing client's proxy settings.


回答1:


You can create your own implementation of HttpRoutePlanner that will allow change of the 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); 
    }
}

Then you can use this DynamicProxyRoutePlanner in your code

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));


来源:https://stackoverflow.com/questions/25567973/apache-httpclient-4-3-5-set-proxy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!