Example usage for org.apache.http.impl.client ProxyAuthenticationStrategy ProxyAuthenticationStrategy

List of usage examples for org.apache.http.impl.client ProxyAuthenticationStrategy ProxyAuthenticationStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl.client ProxyAuthenticationStrategy ProxyAuthenticationStrategy.

Prototype

public ProxyAuthenticationStrategy() 

Source Link

Usage

From source file:de.bytefish.fcmjava.client.tests.FakeFcmClientSettings.java

@Test
public void testFcmClientWithProxySettings() throws Exception {

    // Create Settings:
    IFcmClientSettings settings = new FakeFcmClientSettings();

    // Define the Credentials to be used:
    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();

    // Set the Credentials (any auth scope used):
    basicCredentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("your_username", "your_password"));

    // Create the Apache HttpClientBuilder:
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
            // Set the Proxy Address:
            .setProxy(new HttpHost("your_hostname", 1234))
            // Set the Authentication Strategy:
            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
            // Set the Credentials Provider we built above:
            .setDefaultCredentialsProvider(basicCredentialsProvider);

    // Create the DefaultHttpClient:
    DefaultHttpClient httpClient = new DefaultHttpClient(settings, httpClientBuilder);

    // Finally build the FcmClient:
    try (IFcmClient client = new FcmClient(settings, httpClient)) {
        // TODO Work with the Proxy ...
    }//from  w  ww. java 2s .  c om
}

From source file:eu.esdihumboldt.util.http.client.ClientProxyUtil.java

/**
 * Set-up the given HTTP client to use the given proxy
 * /*from   w  w w . j  a  va  2 s .  co m*/
 * @param builder the HTTP client builder
 * @param proxy the proxy
 * @return the client builder adapted with the proxy settings
 */
public static HttpClientBuilder applyProxy(HttpClientBuilder builder, Proxy proxy) {
    ProxyUtil.init();

    // check if proxy shall be used
    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();

        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        builder = builder.setProxy(proxyHost);

        String user = System.getProperty("http.proxyUser"); //$NON-NLS-1$
        String password = System.getProperty("http.proxyPassword"); //$NON-NLS-1$
        boolean useProxyAuth = user != null && !user.isEmpty();

        if (useProxyAuth) {
            // set the proxy credentials
            CredentialsProvider credsProvider = new BasicCredentialsProvider();

            credsProvider.setCredentials(new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort()),
                    createCredentials(user, password));
            builder = builder.setDefaultCredentialsProvider(credsProvider)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }

        _log.trace("Set proxy to " + proxyAddress.getHostName() + ":" + //$NON-NLS-1$ //$NON-NLS-2$
                proxyAddress.getPort() + ((useProxyAuth) ? (" as user " + user) : (""))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    return builder;
}

From source file:io.getlime.push.service.fcm.FcmClient.java

/**
 * Set information about proxy./* w w w . j  a  v  a 2  s. c  om*/
 * @param host Proxy host URL.
 * @param port Proxy port.
 * @param username Proxy username, use 'null' for proxy without authentication.
 * @param password Proxy user password, ignored in case username is 'null'
 */
public void setProxy(String host, int port, String username, String password) {

    HttpAsyncClientBuilder clientBuilder = HttpAsyncClientBuilder.create();
    clientBuilder.useSystemProperties();
    clientBuilder.setProxy(new HttpHost(host, port));

    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials user = new UsernamePasswordCredentials(username, password);
        credsProvider.setCredentials(new AuthScope(host, port), user);
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    }

    CloseableHttpAsyncClient client = clientBuilder.build();

    HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory();
    factory.setAsyncClient(client);

    restTemplate.setAsyncRequestFactory(factory);
}

From source file:com.angelmmg90.consumerservicespotify.configuration.SpringWebConfig.java

@Bean
public static RestTemplate getTemplate() throws IOException {
    if (template == null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
                new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));

        Header[] h = new Header[3];
        h[0] = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        h[1] = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + ACCESS_TOKEN);

        List<Header> headers = new ArrayList<>(Arrays.asList(h));

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.useSystemProperties();
        clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        clientBuilder.setDefaultHeaders(headers).build();
        String SAMPLE_URL = "https://api.spotify.com/v1/users/yourUserName/playlists/7HHFd1tNiIFIwYwva5MTNv";

        HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();

        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        CloseableHttpClient client = clientBuilder.build();
        client.execute(request);/*from  w  ww.j a va2  s.com*/

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(client);

        template = new RestTemplate();
        template.setRequestFactory(factory);
    }

    return template;
}

From source file:com.googlesource.gerrit.plugins.github.oauth.PooledHttpClientProvider.java

@Override
public HttpClient get() {
    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnPerRoute(maxConnectionPerRoute)
            .setMaxConnTotal(maxTotalConnection);

    if (proxy.getProxyUrl() != null) {
        URL url = proxy.getProxyUrl();
        builder.setProxy(new HttpHost(url.getHost(), url.getPort()));
        if (!Strings.isNullOrEmpty(proxy.getUsername()) && !Strings.isNullOrEmpty(proxy.getPassword())) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(proxy.getUsername(),
                    proxy.getPassword());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), creds);
            builder.setDefaultCredentialsProvider(credsProvider);
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }//w  w w .j  ava 2s.  c  o  m
    }

    return builder.build();
}

From source file:ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory.java

public synchronized HttpClient getNativeHttpClient() {
    if (myHttpClient == null) {

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000,
                TimeUnit.MILLISECONDS);
        connectionManager.setMaxTotal(getPoolMaxTotal());
        connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute());

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout())
                .setConnectTimeout(getConnectTimeout())
                .setConnectionRequestTimeout(getConnectionRequestTimeout()).setStaleConnectionCheckEnabled(true)
                .setProxy(myProxy).build();

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(defaultRequestConfig).disableCookieManagement();

        if (myProxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(myProxy.getHostName(), myProxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credsProvider);
        }//ww w. j a  va  2  s .  c  om

        myHttpClient = builder.build();
        // @formatter:on

    }

    return myHttpClient;
}

From source file:de.tsystems.mms.apm.performancesignature.viewer.rest.model.CustomJenkinsHttpClient.java

private static HttpClientBuilder createHttpClientBuilder(final boolean verifyCertificate,
        final CustomProxy customProxy) {

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.useSystemProperties();
    if (!verifyCertificate) {
        SSLContextBuilder builder = new SSLContextBuilder();
        try {/*from   w w w .  j a  v a 2  s.c  o  m*/
            builder.loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
            httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build()));
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
        }

    }
    if (customProxy != null) {
        Jenkins jenkins = PerfSigUIUtils.getInstance();
        if (customProxy.isUseJenkinsProxy() && jenkins.proxy != null) {
            final ProxyConfiguration proxyConfiguration = jenkins.proxy;
            if (StringUtils.isNotBlank(proxyConfiguration.name) && proxyConfiguration.port > 0) {
                httpClientBuilder.setProxy(new HttpHost(proxyConfiguration.name, proxyConfiguration.port));
                if (StringUtils.isNotBlank(proxyConfiguration.getUserName())) {
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                            proxyConfiguration.getUserName(), proxyConfiguration.getUserName());
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfiguration.name, proxyConfiguration.port),
                            usernamePasswordCredentials);
                    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                    httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        } else {
            httpClientBuilder.setProxy(new HttpHost(customProxy.getProxyServer(), customProxy.getProxyPort()));
            if (StringUtils.isNotBlank(customProxy.getProxyUser())
                    && StringUtils.isNotBlank(customProxy.getProxyPassword())) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                        customProxy.getProxyUser(), customProxy.getProxyPassword());
                credsProvider.setCredentials(
                        new AuthScope(customProxy.getProxyServer(), customProxy.getProxyPort()),
                        usernamePasswordCredentials);
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            }
        }
    }
    return httpClientBuilder;
}

From source file:eu.esdihumboldt.util.http.ProxyUtil.java

/**
 * Set-up the given HTTP client to use the given proxy
 * // w  w  w.j  a va2s  .  c om
 * @param builder the HTTP client builder
 * @param proxy the proxy
 * @return the client builder adapted with the proxy settings
 */
public static HttpClientBuilder applyProxy(HttpClientBuilder builder, Proxy proxy) {
    init();

    // check if proxy shall be used
    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();

        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        builder = builder.setProxy(proxyHost);

        String user = System.getProperty("http.proxyUser"); //$NON-NLS-1$
        String password = System.getProperty("http.proxyPassword"); //$NON-NLS-1$
        boolean useProxyAuth = user != null && !user.isEmpty();

        if (useProxyAuth) {
            // set the proxy credentials
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort()),
                    new UsernamePasswordCredentials(user, password));
            builder = builder.setDefaultCredentialsProvider(credsProvider)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }

        _log.trace("Set proxy to " + proxyAddress.getHostName() + ":" + //$NON-NLS-1$ //$NON-NLS-2$
                proxyAddress.getPort() + ((useProxyAuth) ? (" as user " + user) : (""))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    return builder;
}

From source file:org.openehealth.ipf.commons.ihe.fhir.SslAwareApacheRestfulClientFactory.java

protected synchronized HttpClient getNativeHttpClient() {
    if (httpClient == null) {

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(getConnectTimeout())
                .setSocketTimeout(getSocketTimeout()).setConnectionRequestTimeout(getConnectionRequestTimeout())
                .setProxy(proxy).setStaleConnectionCheckEnabled(true).build();

        HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
                .setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(getPoolMaxTotal())
                .setMaxConnPerRoute(getPoolMaxPerRoute()).setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .disableCookieManagement();

        if (securityInformation != null) {
            securityInformation.configureHttpClientBuilder(builder);
        }/*w  ww .  j a va 2  s. c o  m*/

        // Need to authenticate against proxy
        if (proxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        httpClient = builder.build();
    }

    return httpClient;
}

From source file:org.springframework.cloud.dataflow.rest.util.HttpClientConfigurer.java

/**
 * Configures the {@link HttpClientBuilder} with a proxy host. If the
 * {@code proxyUsername} and {@code proxyPassword} are not {@code null}
 * then a {@link CredentialsProvider} is also configured for the proxy host.
 *
 * @param proxyUri Must not be null and must be configured with a scheme (http or https).
 * @param proxyUsername May be null//from   w  w w. j a v a  2 s . c om
 * @param proxyPassword May be null
 * @return a reference to {@code this} to enable chained method invocation
 */
public HttpClientConfigurer withProxyCredentials(URI proxyUri, String proxyUsername, String proxyPassword) {

    Assert.notNull(proxyUri, "The proxyUri must not be null.");
    Assert.hasText(proxyUri.getScheme(), "The scheme component of the proxyUri must not be empty.");

    httpClientBuilder.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()));
    if (proxyUsername != null && proxyPassword != null) {
        final CredentialsProvider credentialsProvider = this.getOrInitializeCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()),
                new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    }
    return this;
}