標籤:
Even though HttpClient is aware of complex routing scemes and proxy chaining, it supports only simple direct or one hop proxy connections out of the box.
The simplest way to tell HttpClient to connect to the target host via a proxy is by setting the default proxy parameter:
HttpHost proxy = new HttpHost("someproxy", 8080);DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);CloseableHttpClient httpclient = HttpClients.custom() .setRoutePlanner(routePlanner) .build();
One can also instruct HttpClient to use the standard JRE proxy selector to obtain proxy information:
SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());CloseableHttpClient httpclient = HttpClients.custom() .setRoutePlanner(routePlanner) .build();
Alternatively, one can provide a custom RoutePlanner implementation in order to have a complete control over the process of HTTP route computation:
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(); }}
如果想針對不同的請求設定不同的代理,可以通過 RequestConfig 設定代理,然後在執行請求時帶上 RequestConfig 參數。
CloseableHttpClient httpClient = HttpClients.createDefault();HttpHost proxy = new HttpHost("someproxy", 8080);RequestConfig config = RequestConfig.custom().setProxy(proxy).build();HttpGet httpGet = new HttpGet("http://example.com"); httpGet.setConfig(config);CloseableHttpResponse response = httpClient.execute(httpGet);
HttpClient(4.3.5) - HttpClient Proxy Configuration