Apache HttpClient 4.3.5 set proxy

I seem to be able to specify the proxy when I create a new one 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 change the existing client proxy settings.

+3


source to share


1 answer


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

      

+7


source







All Articles