1void customizeHttpClient(HttpClient httpClient) throws URISyntaxException { 2 URI proxyURI = new URI("http://proxyhost:proxyport"); 3 AuthenticationStore auth = httpClient.getAuthenticationStore(); 4 // Proxy credentials. 5 auth.addAuthentication(new BasicAuthentication( 6 proxyURI, 7 "Websense Content Gateway", // 认证域 8 "username", // 认证用户 9 "passwd")); // 认证密码 10 11 ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration(); 12 HttpProxy proxy = new HttpProxy(proxyURI.getHost(), proxyURI.getPort()); 13 proxyConfig.getProxies().add(proxy); 14}
其中认证域的值是407 Proxy Authorization Required响应头中Proxy-Authenticate: Basic realm="Websense Content Gateway"的引号部分。
如上配置后,就可以用jetty的HttpClient通过代理发送http请求了。
而在使用jetty-proxy模块做透明代理时,由于AbstractProxyServlet在调用createHttpClient()方法的最后,清空了ProtocolHandler(9.2.10.v20150310版本例外),导致如果jetty-proxy向upstream的请求需通过代理的话,那么以上的配置方式不起作用, jetty-proxy不能自动配置代理认证,提示请求需要代理认证。
所以还需要在调用 createHttpClient ()方法后,添加一个ProxyAuthenticationProtocolHandler。
httpClient.getProtocolHandlers().put(new ProxyAuthenticationProtocolHandler(httpClient));
代码适用jetty.version=9.4.6.v20170531