HttpClient代理伺服器配置
阿新 • • 發佈:2019-02-15
使用代理伺服器最簡單的方式就是,指定一個預設的proxy引數。
HttpHost proxy = new HttpHost("someproxy", 8080);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
我們也可以讓HttpClient去使用jre的代理伺服器。
SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(
ProxySelector.getDefault());
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
又或者,我們也可以手動配置RoutePlanner,這樣就可以完全控制Http路由的過程。
HttpRoutePlanner routePlanner = new HttpRoutePlanner() { public HttpRoute determineRoute( HttpHost target, HttpRequest request, HttpContext context) throws HttpException { return new HttpRoute(target, null, new HttpHost("someproxy", 8080), "https".equalsIgnoreCase(target.getSchemeName())); } }; CloseableHttpClient httpclient = HttpClients.custom() .setRoutePlanner(routePlanner) .build(); } }
可以封裝成一個方法來獲取一個proxyHttpClient例項:
public static CloseableHttpClient getProxyHttpClient(IP ip){ HttpHost proxy=new HttpHost(ip.getHost(),ip.getPort()); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); CloseableHttpClient proxyHttpClient=HttpClients.custom().setRoutePlanner(routePlanner).build(); return proxyHttpClient; }