java Apache HttpClient 4.3.5 设置代理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25567973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Apache HttpClient 4.3.5 set proxy
提问by Ilgiz Mustafin
It seems that I can specify the proxy when I construct new HttpClient
with:
似乎我可以在构造 new 时指定代理HttpClient
:
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
取自http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e475
Is it possible to modify existing client's proxy settings.
是否可以修改现有客户端的代理设置。
回答by Filip Nguyen
You can create your own implementation of HttpRoutePlanner that will allow change of the HttpHost.
您可以创建自己的 HttpRoutePlanner 实现,以允许更改 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
然后你可以在你的代码中使用这个 DynamicProxyRoutePlanner
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));