gorootde
gorootde

Reputation: 4073

How to use Proxy authentication with Jersey and Apache Http client?

I am using jersey client with 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);

But how to add username and password for Proxy authentication?

Seems like apache connection provider does not use the standard java proxy selector mechanisms.

Upvotes: 1

Views: 3757

Answers (2)

Pradeep Poojari
Pradeep Poojari

Reputation: 165

I think you should add few more lines of code

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

otherwise it wont really authenticate the proxy host I feel. In your case it might be bypassing the proxy. ?

Upvotes: 0

gorootde
gorootde

Reputation: 4073

I finally found the solution by myself. Unfortunately this is documented nowhere:

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);

Upvotes: 2

Related Questions