Jetty的HttpClient設置代理

void customizeHttpClient(HttpClient httpClient) throws URISyntaxException {
    URI proxyURI = new URI("http://proxyhost:proxyport");
    AuthenticationStore auth = httpClient.getAuthenticationStore();
    // Proxy credentials.
    auth.addAuthentication(new BasicAuthentication(
            proxyURI,
            "Websense Content Gateway", // 認證域
            "username", // 認證用戶
            "passwd")); // 認證密碼
    
    ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();
    HttpProxy proxy = new HttpProxy(proxyURI.getHost(), proxyURI.getPort());
    proxyConfig.getProxies().add(proxy);
}

其中認證域的值是407 Proxy Authorization Required響應頭中Proxy-Authenticate: Basic realm="Websense Content Gateway"的引號部分。java

如上配置後,就能夠用jetty的HttpClient經過代理髮送http請求了。ui

而在使用jetty-proxy模塊作透明代理時,因爲AbstractProxyServlet在調用createHttpClient()方法的最後,清空了ProtocolHandler(9.2.10.v20150310版本例外),致使若是jetty-proxy向upstream的請求需經過代理的話,那麼以上的配置方式不起做用, jetty-proxy不能自動配置代理認證,提示請求須要代理認證。代理

因此還須要在調用 createHttpClient ()方法後,添加一個ProxyAuthenticationProtocolHandler。code

httpClient.getProtocolHandlers().put(new ProxyAuthenticationProtocolHandler(httpClient));

代碼適用jetty.version=9.4.6.v20170531get

相關文章
相關標籤/搜索