1. 程式人生 > >《HttpClient官方文件》2.8 HttpClient代理配置

《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();
    }
}