Example usage for org.apache.http.impl.client HttpClientBuilder setProxy

List of usage examples for org.apache.http.impl.client HttpClientBuilder setProxy

Introduction

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

Prototype

public final HttpClientBuilder setProxy(final HttpHost proxy) 

Source Link

Document

Assigns default proxy value.

Usage

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Handler main//www. j a va  2s  .  c  om
 *
 * @param targetHost target {@link HttpHost}
 * @param proxyHost proxy {@link HttpHost}
 * @param httpRequestMethod HttpGet or HttpPost...
 * @param encoding encoding
 * @param upc {@link UsernamePasswordCredentials}
 * @param keystore keystore stream
 * @param password keystore password
 * @return result String
 * @throws IOException  if an I/O error occurs
 */
protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod,
        String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password)
        throws IOException {

    HttpClientBuilder hcb = HttpClients.custom();
    hcb.setDefaultRequestConfig(getRequestConfig());
    if (proxyHost != null) {
        hcb.setProxy(proxyHost);
    }
    if (keystore != null) {

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(keystore, password);
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext);
            hcb.setSSLSocketFactory(ssf);
        } catch (KeyStoreException e) {
            log.error("{}", e.getMessage(), e);
        } catch (CertificateException e) {
            log.error("{}", e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
        } catch (KeyManagementException e) {
            log.error("{}", e.getMessage(), e);
        } finally {
            keystore.close();
        }

    }

    if (upc != null) {
        CredentialsProvider cp = new BasicCredentialsProvider();

        AuthScope as = new AuthScope(targetHost);

        cp.setCredentials(as, upc);
        hcb.setDefaultCredentialsProvider(cp);
    }

    CloseableHttpClient chc = hcb.build();
    try {
        CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod);
        return getResponse(response, encoding);
    } finally {
        chc.close();
    }

}

From source file:org.eclipse.jgit.transport.http.apache.HttpClientConnection.java

private HttpClient getClient() {
    if (client == null) {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
            isUsingProxy = true;//from w  w w .ja v  a2  s.co  m
            InetSocketAddress adr = (InetSocketAddress) proxy.address();
            clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
        }
        if (timeout != null) {
            configBuilder.setConnectTimeout(timeout.intValue());
        }
        if (readTimeout != null) {
            configBuilder.setSocketTimeout(readTimeout.intValue());
        }
        if (followRedirects != null) {
            configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
        }
        if (hostnameverifier != null) {
            SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(),
                    hostnameverifier);
            clientBuilder.setSSLSocketFactory(sslConnectionFactory);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionFactory)
                    .register("http", PlainConnectionSocketFactory.INSTANCE).build();
            clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        }
        clientBuilder.setDefaultRequestConfig(configBuilder.build());
        client = clientBuilder.build();
    }

    return client;
}

From source file:com.github.technosf.posterer.modules.commons.transport.CommonsRequestModelImpl.java

/**
 * Configures builder for the given proxy
 * //from w  ww  .  j  ava 2s  .  c  o m
 * @param builder
 *            the builder to configure
 * @param proxy
 *            the proxy info
 */
private void buildInProxy(Auditor auditor, HttpClientBuilder builder, final Proxy proxy) {
    HttpHost httpproxy = new HttpHost(proxy.getProxyHost(), Integer.parseInt(proxy.getProxyPort()));

    if (!proxy.getProxyUser().isEmpty())
    /* 
     * Add proxy auth
     */
    {
        // TODO Implement proxy auth
        //ProxyAuthenticationStrategy auth = new ProxyAuthenticationStrategy();
    }
    builder.setProxy(httpproxy);
}

From source file:org.asqatasun.util.http.HttpRequestHandler.java

private CloseableHttpClient getHttpClient(String url) {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).build();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
    httpClientBuilder.setUserAgent(ASQATASUN_USER_AGENT);
    if (isProxySet(url)) {
        LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort));
        httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort)));
        if (isProxyCredentialSet()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser
                    + " and " + proxyPassword));
        }/*from  ww  w.j  a  v a2  s .c om*/
    }
    return httpClientBuilder.build();
}

From source file:com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigSettings.java

/**
 * Update the given {@link HttpClientBuilder} object with the appropriate
 * settings from configuration./*  w  w w . j av a  2  s. co m*/
 * 
 * @param httpClientBuilder
 *            The object to update.
 * @return The updates httpClientBuilder
 */
public HttpClientBuilder applyConfig(HttpClientBuilder httpClientBuilder) {
    if (properties
            .containsKey(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY)) {
        httpClientBuilder.setSSLSocketFactory((LayeredConnectionSocketFactory) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER)) {
        httpClientBuilder.setConnectionManager((HttpClientConnectionManager) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI)) {
        httpClientBuilder.setProxy(new HttpHost(
                (String) properties.get(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI)));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER)) {
        httpClientBuilder.setRetryHandler((HttpRequestRetryHandler) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER)) {
        return (HttpClientBuilder) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER);
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY)) {
        httpClientBuilder.setRedirectStrategy((DefaultRedirectStrategy) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY));

        // Currently the redirect strategy, due to what seems to be a bug,
        // fails for post requests since it tries do double
        // add the content-length header. This workaround makes sure this header is always
        // removed before it is actually processed by apache
        httpClientBuilder.addInterceptorFirst(new HttpHeaderRemovalFilter());
    }

    if (properties.containsKey("AuthFilter")) {
        @SuppressWarnings("unchecked")
        ServiceRequestFilter filter = (ServiceRequestFilter) properties.get("AuthFilter");
        httpClientBuilder.addInterceptorFirst(new FilterInterceptor(filter));
    }

    if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_HOST)
            && properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_PORT)) {
        String proxyHost = (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_HOST);
        int proxyPort = Integer
                .parseInt((String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_PORT));
        HttpHost proxy;
        if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME)) {
            proxy = new HttpHost(proxyHost, proxyPort,
                    (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME));
        } else {
            proxy = new HttpHost(proxyHost, proxyPort);
        }
        httpClientBuilder.setProxy(proxy);
    }

    return httpClientBuilder;
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Set the request builder based on the request
 * /*from  www .  ja v a2  s .co  m*/
 * @param proxy The request Proxy options
 * @param httpClientBuilder The request builder
 * @throws Exception
 */
private void setProxy(final Proxy proxy, final HttpClientBuilder httpClientBuilder,
        final Builder requestConfigurationBuilder) {
    if (proxy != null) {
        final HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort());

        httpClientBuilder.setProxy(httpHost);
        httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        requestConfigurationBuilder.setProxy(httpHost);
        final ArrayList<String> authPrefs = new ArrayList<>();
        authPrefs.add(AuthSchemes.BASIC);
        requestConfigurationBuilder.setProxyPreferredAuthSchemes(authPrefs);
    }
}

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare connection//from w w  w . jav  a  2  s  .  c o  m
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException the eWS http exception
 */
@Override
public void prepareConnection() throws EWSHttpException {
    try {
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        if (getProxy() != null) {
            HttpHost proxy = new HttpHost(getProxy().getHost(), getProxy().getPort());
            builder.setProxy(proxy);

            if (HttpProxyCredentials.isProxySet()) {
                NTCredentials cred = new NTCredentials(HttpProxyCredentials.getUserName(),
                        HttpProxyCredentials.getPassword(), "", HttpProxyCredentials.getDomain());
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxy), cred);
                builder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        if (getUserName() != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(getUserName(), getPassword(), "", getDomain()));
            builder.setDefaultCredentialsProvider(credsProvider);
        }

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setAuthenticationEnabled(true);
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setRedirectsEnabled(isAllowAutoRedirect());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        if (getUserName() != null) {
            ArrayList<String> authPrefs = new ArrayList<String>();
            authPrefs.add(AuthSchemes.NTLM);
            rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        }
        //
        builder.setDefaultRequestConfig(rcBuilder.build());

        httpPostReq = new HttpPost(getUrl().toString());
        httpPostReq.addHeader("Content-type", getContentType());
        //httpPostReq.setDoAuthentication(true);
        httpPostReq.addHeader("User-Agent", getUserAgent());
        httpPostReq.addHeader("Accept", getAccept());
        httpPostReq.addHeader("Keep-Alive", "300");
        httpPostReq.addHeader("Connection", "Keep-Alive");

        if (isAcceptGzipEncoding()) {
            httpPostReq.addHeader("Accept-Encoding", "gzip,deflate");
        }

        if (getHeaders().size() > 0) {
            for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) {
                httpPostReq.addHeader(httpHeader.getKey(), httpHeader.getValue());
            }
        }

        //create the client
        client = builder.build();
    } catch (Exception er) {
        er.printStackTrace();
    }
}

From source file:com.urswolfer.intellij.plugin.gerrit.rest.ProxyHttpClientBuilderExtension.java

@Override
public CredentialsProvider extendCredentialProvider(HttpClientBuilder httpClientBuilder,
        CredentialsProvider credentialsProvider, GerritAuthData authData) {
    HttpConfigurable proxySettings = HttpConfigurable.getInstance();
    IdeaWideProxySelector ideaWideProxySelector = new IdeaWideProxySelector(proxySettings);

    // This will always return at least one proxy, which can be the "NO_PROXY" instance.
    List<Proxy> proxies = ideaWideProxySelector.select(URI.create(authData.getHost()));

    // Find the first real proxy with an address type we support.
    for (Proxy proxy : proxies) {
        SocketAddress socketAddress = proxy.address();

        if (HttpConfigurable.isRealProxy(proxy) && socketAddress instanceof InetSocketAddress) {
            InetSocketAddress address = (InetSocketAddress) socketAddress;
            HttpHost proxyHttpHost = new HttpHost(address.getHostName(), address.getPort());
            httpClientBuilder.setProxy(proxyHttpHost);

            // Here we use the single username/password that we got from IDEA's settings. It feels kinda strange
            // to use these credential but it's probably what the user expects.
            if (proxySettings.PROXY_AUTHENTICATION) {
                AuthScope authScope = new AuthScope(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                        proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword());
                credentialsProvider.setCredentials(authScope, credentials);
                break;
            }// ww w. j  a  va  2 s . c om
        }
    }
    return credentialsProvider;
}

From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestExecutor.java

/**
 * Creates a new {@code HttpClientRequestExecutor} using the specified {@code ClientCredentials} and optional {@code Proxy}
 * configuration.//from   w w w  . ja  va 2  s.  c o  m
 * @param clientCredentials the Okta account API Key that will be used to authenticate the client with Okta's API sever
 * @param proxy the HTTP proxy to be used when communicating with the Okta API server (can be null)
 * @param authenticationScheme the HTTP authentication scheme to be used when communicating with the Okta API server.
 *                             If null, then SSWS will be used.
 */
public HttpClientRequestExecutor(ClientCredentials clientCredentials, Proxy proxy,
        AuthenticationScheme authenticationScheme, RequestAuthenticatorFactory requestAuthenticatorFactory,
        Integer connectionTimeout) {
    Assert.notNull(clientCredentials, "clientCredentials argument is required.");
    Assert.isTrue(connectionTimeout >= 0, "Timeout cannot be a negative number.");

    RequestAuthenticatorFactory factory = (requestAuthenticatorFactory != null) ? requestAuthenticatorFactory
            : new DefaultRequestAuthenticatorFactory();

    this.requestAuthenticator = factory.create(authenticationScheme, clientCredentials);

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();

    if (MAX_CONNECTIONS_TOTAL >= MAX_CONNECTIONS_PER_ROUTE) {
        connMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(MAX_CONNECTIONS_TOTAL);
    } else {
        connMgr.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(DEFAULT_MAX_CONNECTIONS_TOTAL);

        log.warn(
                "{} ({}) is less than {} ({}). "
                        + "Reverting to defaults: connectionMaxTotal ({}) and connectionMaxPerRoute ({}).",
                MAX_CONNECTIONS_TOTAL_PROPERTY_KEY, MAX_CONNECTIONS_TOTAL,
                MAX_CONNECTIONS_PER_ROUTE_PROPERTY_KEY, MAX_CONNECTIONS_PER_ROUTE,
                DEFAULT_MAX_CONNECTIONS_TOTAL, DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    }

    // The connectionTimeout value is specified in seconds in Okta configuration settings.
    // Therefore, multiply it by 1000 to be milliseconds since RequestConfig expects milliseconds.
    int connectionTimeoutAsMilliseconds = connectionTimeout * 1000;

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeoutAsMilliseconds)
            .setSocketTimeout(connectionTimeoutAsMilliseconds).setRedirectsEnabled(false).build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .disableCookieManagement().setDefaultConnectionConfig(connectionConfig)
            .setConnectionManager(connMgr);

    this.httpClientRequestFactory = new HttpClientRequestFactory(requestConfig);

    if (proxy != null) {
        //We have some proxy setting to use!
        HttpHost httpProxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        httpClientBuilder.setProxy(httpProxyHost);

        if (proxy.isAuthenticationRequired()) {
            AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort());
            Credentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
            CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider();
            credentialsProviderProvider.setCredentials(authScope, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderProvider);
        }
    }

    this.httpClient = httpClientBuilder.build();
}