Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache HttpClient 4.3.5 set proxy

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.

like image 612
Ilgiz Mustafin Avatar asked Aug 29 '14 12:08

Ilgiz Mustafin


1 Answers

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));
like image 52
Filip Nguyen Avatar answered Nov 02 '22 23:11

Filip Nguyen