《HttpClient官方文檔》2.8 HttpClient代理配置
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(); } }
最後更新:2017-05-19 12:04:29