如何使用Jersey和Apache Http客户端进行代理身份验证?

时间:2016-04-28 08:21:55

标签: java apache proxy jersey

我正在使用带有ApacheConnection Provider的泽西客户端。

    Builder builder = RequestConfig.custom().setConnectTimeout(timeout);
    List<Proxy> proxies = ProxyManager.getInstance().select(baseUrl.toURI());
    if (useProxy) {
        ...
        builder.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort()));
    }
    RequestConfig requestConfig = builder.build();

    final ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);
    clientConfig.connectorProvider(new ApacheConnectorProvider());

    client = ClientBuilder.newBuilder().withConfig(clientConfig).sslContext(getSSLContext()).build();
    client.property(ClientProperties.CONNECT_TIMEOUT, 5000);

但是如何为代理身份验证添加用户名和密码?

似乎apache连接提供程序不使用标准的java代理选择器机制。

2 个答案:

答案 0 :(得分:2)

我终于找到了解决方案。不幸的是,这无处可见:

HttpHost proxyhost = new HttpHost(host,pw);

CredentialsProvider credsProvider = new BasicCredentialsProvider();

credsProvider.setCredentials(new AuthScope(proxyhost), new UsernamePasswordCredentials(user, pw));
clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credsProvider);

builder.setProxy(proxyhost);

答案 1 :(得分:0)

我认为您应该再添加几行代码

builder.setProxy(proxyhost).setDefaultCredentialsProvider(credsProvider)
                            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

否则,它不会真正对我感觉到的代理主机进行身份验证。在您的情况下,它可能会绕过代理。 ?