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:org.sonatype.nexus.internal.httpclient.HttpClientManagerImplIT.java

private void testPrepareHttpClientBuilderHttpRequest(boolean isSSL, boolean isProxy) throws Exception {
    // Setup// w w w  .j a  va 2  s  .co  m
    HttpClientBuilder builder = underTest.prepare(plan -> plan.setUserAgentBase(EXPECTED_USER_AGENT));
    builder.setConnectionManager(null);
    if (isProxy) {
        builder.setProxy(new HttpHost(proxyServer.getHostName(), proxyServer.getPort()));
    }
    if (isSSL) {
        setSSL(builder);
    }

    String url;
    if (isSSL) {
        url = "https://" + targetServerSSL.getUrl().getHost() + ":" + targetServerSSL.getPort();
    } else {
        url = "http://" + targetServer.getUrl().getHost() + ":" + targetServer.getPort();
    }

    CloseableHttpResponse resp = null;
    // Execute
    try (CloseableHttpClient client = builder.build()) {
        resp = client.execute(new HttpGet(new URI(url)));
    } finally {
        if (resp != null) {
            resp.close();
        }
    }

    // Verify
    assertThat(resp.getStatusLine().getStatusCode(), equalTo(HttpStatus.OK));
    if (isSSL) {
        assertThat(httpsValidatingBehaviour.getSuccessCount(), equalTo(1));
    } else {
        assertThat(httpValidatingBehaviour.getSuccessCount(), equalTo(1));
    }
    if (isProxy) {
        if (isSSL) {
            // Only one filterable request in SSL (CONNECT) without using MITM
            assertThat(proxyServer.getSuccessCount(), equalTo(1));
        } else {
            // Two filterable requests in non-SSL (initiate and real request)
            assertThat(proxyServer.getSuccessCount(), equalTo(2));
        }
    }
}

From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob2.java

@Override
public String call() throws IOException {
    String response = "";
    ReviewInput reviewInput = createReview();

    String reviewEndpoint = resolveEndpointURL();

    HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint);

    if (httpPost == null) {
        return response;
    }/*from   ww w.  j a va  2 s.  co  m*/

    CredentialsProvider credProvider = new BasicCredentialsProvider();
    credProvider.setCredentials(AuthScope.ANY, credentials);

    HttpHost proxy = null;
    if (httpProxy != null && !httpProxy.isEmpty()) {
        try {
            URL url = new URL(httpProxy);
            proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        } catch (MalformedURLException e) {
            logger.error("Could not parse proxy URL, attempting without proxy.", e);
            if (altLogger != null) {
                altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage());
            }
        }
    }

    HttpClientBuilder builder = HttpClients.custom();
    builder.setDefaultCredentialsProvider(credProvider);
    if (proxy != null) {
        builder.setProxy(proxy);
    }
    CloseableHttpClient httpClient = builder.build();

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");

        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase());
            if (altLogger != null) {
                altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase());
            }
        }
    } catch (Exception e) {
        logger.error("Failed to submit result to Gerrit", e);
        if (altLogger != null) {
            altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString());
        }
    }
    return response;
}

From source file:edu.emory.bmi.medicurator.tcia.TciaQuery.java

private HttpClient getInsecureClient() throws Exception {
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }/*  w w  w  .  ja  va2 s.  c  o  m*/
    }).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSSLSocketFactory(sslsf);
    if (Constants.PROXY_HOST != null && Constants.PROXY_PORT != null) {
        HttpHost proxy = new HttpHost(Constants.PROXY_HOST, Constants.PROXY_PORT, "http");
        builder.setProxy(proxy);
    }
    if (Constants.PROXY_USERNAME != null && Constants.PROXY_PASSWORD != null) {
        Credentials credentials = new UsernamePasswordCredentials(Constants.PROXY_USERNAME,
                Constants.PROXY_PASSWORD);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, credentials);
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    return builder.build();
}

From source file:com.hp.autonomy.frontend.find.hod.beanconfiguration.HodConfiguration.java

@Bean
public HttpClient httpClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    final String proxyHost = environment.getProperty("find.https.proxyHost");

    if (proxyHost != null) {
        final Integer proxyPort = Integer.valueOf(environment.getProperty("find.https.proxyPort", "8080"));
        builder.setProxy(new HttpHost(proxyHost, proxyPort));
    }// w w  w.  j  av a 2 s  . c o m

    builder.disableCookieManagement();

    return builder.build();
}

From source file:org.attribyte.api.http.impl.commons.Commons4Client.java

private void initFromOptions(final ClientOptions options) {

    if (options != ClientOptions.IMPLEMENTATION_DEFAULT) {

        HttpClientBuilder builder = HttpClients.custom();
        builder.setMaxConnTotal(options.maxConnectionsTotal);
        builder.setMaxConnPerRoute(options.maxConnectionsPerDestination);
        builder.setUserAgent(options.userAgent);
        if (options.proxyHost != null) {
            builder.setProxy(new HttpHost(options.proxyHost, options.proxyPort));
        }/*from  ww w. ja v a  2 s .  c o m*/

        this.defaultRequestConfig = RequestConfig.custom().setConnectTimeout(options.connectionTimeoutMillis)
                .setConnectionRequestTimeout(options.requestTimeoutMillis)
                .setRedirectsEnabled(RequestOptions.DEFAULT_FOLLOW_REDIRECTS)
                .setMaxRedirects(RequestOptions.DEFAULT_FOLLOW_REDIRECTS ? 5 : 0)
                .setAuthenticationEnabled(false).setCircularRedirectsAllowed(false)
                .setSocketTimeout(options.socketTimeoutMillis).build();
        builder.setDefaultRequestConfig(defaultRequestConfig);

        ConnectionConfig connectionConfig = ConnectionConfig.custom()
                .setBufferSize(
                        options.requestBufferSize > options.responseBufferSize ? options.requestBufferSize
                                : options.responseBufferSize)
                .build();
        builder.setDefaultConnectionConfig(connectionConfig);

        this.httpClient = builder.build();
    } else {
        this.defaultRequestConfig = RequestConfig.DEFAULT;
        this.httpClient = HttpClients.createDefault();
    }
}

From source file:com.github.tmyroadctfig.icloud4j.ICloudService.java

/**
 * Creates a new iCloud service instance
 *
 * @param clientId the client ID.//from   w ww  .  j a v a2  s.  co m
 */
@SuppressWarnings("deprecation")
public ICloudService(ICloudSession session) {
    this.session = session;
    try {
        HttpClientBuilder clientBuilder = HttpClientBuilder.create().setDefaultCookieStore(getCookieStore());

        if (!Strings.isNullOrEmpty(PROXY_HOST)) {
            clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
        }

        if (DISABLE_SSL_CHECKS) {
            clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSslcontext(
                    new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true).build());
        }

        httpClient = clientBuilder.build();

    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

    idmsaService = new IdmsaService(this);
}

From source file:org.iipg.hurricane.jmx.client.JMXClientBuilder.java

private void setupProxyIfNeeded(HttpClientBuilder builder) {
    if (httpProxy != null) {
        builder.setProxy(new HttpHost(httpProxy.getHost(), httpProxy.getPort()));
        if (httpProxy.getUser() != null) {
            AuthScope proxyAuthScope = new AuthScope(httpProxy.getHost(), httpProxy.getPort());
            UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(httpProxy.getUser(),
                    httpProxy.getPass());
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(proxyAuthScope, proxyCredentials);
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }/* w  w  w.j a va  2  s  .co m*/
    }
}

From source file:com.brsanthu.googleanalytics.GoogleAnalytics.java

protected CloseableHttpClient createHttpClient(GoogleAnalyticsConfig config) {
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute(config));

    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connManager);

    if (isNotEmpty(config.getUserAgent())) {
        builder.setUserAgent(config.getUserAgent());
    }/*  www  . j  a  v  a2s  . c  om*/

    if (isNotEmpty(config.getProxyHost())) {
        builder.setProxy(new HttpHost(config.getProxyHost(), config.getProxyPort()));

        if (isNotEmpty(config.getProxyUserName())) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUserName(), config.getProxyPassword()));
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }

    return builder.build();
}

From source file:com.terracotta.nrplugin.rest.nr.MetricReporter.java

@PostConstruct
private void init() {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();
    HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig);
    if (useProxy) {
        int parsedProxyPort = 8080;
        try {/*from w  w w  .j  a v  a2  s. c  o m*/
            parsedProxyPort = Integer.parseInt(proxyPort);
        } catch (NumberFormatException e) {
            log.warn("Could not parse the proxyPort. Defaulting to 8080.");
            parsedProxyPort = 8080;
        }

        HttpHost proxy = new HttpHost(proxyHostname, parsedProxyPort, proxyScheme);
        httpClientBuilder.setProxy(proxy);
        log.info("Configuring HttpClient with proxy '" + proxy.toString() + "'");
    }
    httpClient = httpClientBuilder.build();
}