Apache HttpClient 4.3.5 set proxy

12,785

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));
Share:
12,785
Ilgiz Mustafin
Author by

Ilgiz Mustafin

I think I like helping people :P #SOreadytohelp

Updated on June 04, 2022

Comments

  • Ilgiz Mustafin
    Ilgiz Mustafin almost 2 years

    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.