閱讀373 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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

轉載自 並發編程網 - ifeve.com

最後更新:2017-05-19 12:04:29

  上一篇:go  用戶瀏覽體驗度為什麼能夠決定網站的成敗?!
  下一篇:go  如何安裝 pandom : 一個針對 Linux 的真隨機數生成器