2.8. HttpClient代理配置
即使HttpClient意识到路由方案和代理连接的复杂性,它也只支持简单直连或单跳代理连接的开箱即用。
通知HttpClient连接到目标主机,最简单的方法是通过设置默认参数的代理:
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();
或者,可以利用customRoutePlanner接口的实现类来完全控制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(); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/114009.html