Apache HttpClient 4.3.5 set proxy

前端 未结 1 1099
走了就别回头了
走了就别回头了 2020-12-28 23:54

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

HttpHost proxy = new HttpHost(\"someproxy\", 8080);
DefaultProxyRout         


        
相关标签:
1条回答
  • 2020-12-29 00:44

    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));
    
    0 讨论(0)
提交回复
热议问题