Example usage for org.apache.http.impl.client HttpClients custom

List of usage examples for org.apache.http.impl.client HttpClients custom

Introduction

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

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactoryIntegrationTest.java

private static void createClient() throws Exception {
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create();

    socketFactoryRegistry.register("http", PlainConnectionSocketFactory.INSTANCE);

    socketFactoryRegistry.register("https", createSSLSocketFactory());

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry.build());
    connMgr.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    connMgr.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//from ww  w.ja  v  a2s . c om
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(timeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(connMgr);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    client = cb.build();
}

From source file:com.meltmedia.cadmium.cli.AbstractAuthorizedOnly.java

/**
 * Sets the Commons HttpComponents to accept all SSL Certificates.
 * /*  ww  w  .  j  a  v  a2  s.co m*/
 * @throws Exception
 * @return An instance of HttpClient that will accept all.
 */
protected static HttpClient httpClient() throws Exception {
    return HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
            .setSslcontext(SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                        throws CertificateException {
                    return true;
                }
            }).build()).build();
}

From source file:com.github.segator.scaleway.api.ScalewayClient.java

public ScalewayClient(String accessToken, String organizationToken, ScalewayComputeRegion region) {
    this.accessToken = accessToken;
    this.organizationToken = organizationToken;
    this.region = region;
    HttpClientBuilder httpBuilder = HttpClients.custom();
    httpBuilder.setUserAgent(ScalewayConstants.USER_AGENT);
    this.httpclient = httpBuilder.build();
}

From source file:com.floragunn.searchguard.HeaderAwareJestClientFactory.java

private CloseableHttpClient createHttpClient(final HttpClientConnectionManager connectionManager) {
    return configureHttpClient(HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultRequestConfig(createRequestConfig())).setRoutePlanner(getRoutePlanner()).build();
}

From source file:eu.itesla_project.histodb.client.impl.HistoDbHttpClientImpl.java

private synchronized CloseableHttpClient getHttpclient(HistoDbConfig config) {
    if (httpClient == null) {
        try {//from  ww w .  j a  va 2  s .  co  m
            ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } };
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", plainsf).register("https", sslsf).build();
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
            cm.setDefaultMaxPerRoute(10);
            cm.setMaxTotal(20);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(cm);
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(
                    new AuthScope(new HttpHost(config.getConnectionParameters().getHost(),
                            config.getConnectionParameters().getPort())),
                    new UsernamePasswordCredentials(config.getConnectionParameters().getUserName(),
                            config.getConnectionParameters().getPassword()));
            if (config.getProxyParameters() != null) {
                HttpHost proxy = new HttpHost(config.getProxyParameters().getHost(),
                        config.getProxyParameters().getPort());
                credentialsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(
                        config.getProxyParameters().getUserName(), config.getProxyParameters().getPassword()));
                httpClientBuilder.setProxy(proxy);
            }
            httpClient = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).build();
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    return httpClient;
}

From source file:org.squashtest.tm.plugin.testautomation.jenkins.internal.net.HttpClientProvider.java

public HttpClientProvider() {
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
    manager.setMaxTotal(25);//from  w  w w .j  av a 2 s.co  m

    client = HttpClients.custom().setConnectionManager(manager)
            .addInterceptorFirst(new PreemptiveAuthInterceptor())
            .setDefaultCredentialsProvider(credentialsProvider).build();

    requestFactory = new HttpComponentsClientHttpRequestFactory(client);
}

From source file:com.comcast.csv.drivethru.api.HTTPRequestManager.java

/**
 * Creates a HttpClient object.// www .j a v  a  2s .  c o  m
 * @return client
 */
private CloseableHttpClient createHttpClient() {
    CloseableHttpClient client = null;

    if (mSocketFactory != null && mUrl.startsWith("https")) {
        client = HttpClients.custom().setSSLSocketFactory(mSocketFactory).build();
    } else {
        client = HttpClients.custom().build();
    }

    return client;
}

From source file:org.jboss.as.test.integration.web.security.authentication.BasicAuthenticationMechanismPicketboxRemovedTestCase.java

/**
 * Test checks if correct response is returned after the EJB is called from the secured servlet.
 *
 * @param url/*  ww  w.  j  a  va 2 s .  c o m*/
 * @throws Exception
 */
@Test
public void test(@ArquillianResource URL url) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(USER, PASSWORD));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(url.toExternalForm() + "SecuredEJBServlet/");
        HttpResponse response = httpclient.execute(httpget);
        assertNotNull("Response is 'null', we expected non-null response!", response);
        String text = Utils.getContent(response);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertTrue("User principal different from what we expected!", text.contains("Principal: " + USER));
        assertTrue("Remote user different from what we expected!", text.contains("Remote User: " + USER));
        assertTrue("Authentication type different from what we expected!",
                text.contains("Authentication Type: BASIC"));
    }
}

From source file:dev.snowdrop.example.OpenShiftIT.java

/**
 * We need a simplified setup that allows us to work with self-signed certificates.
 * To support this we need to provide a custom http client.
 *///  w w  w.java2  s . co  m
private AuthzClient createAuthzClient() throws Exception {
    InputStream configStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("keycloak.json");
    if (configStream == null) {
        throw new IllegalStateException("Could not find any keycloak.json file in classpath.");
    }

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial((chain, authType) -> true).build();
    HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();

    // the injected @RouteURL always contains a port number, which means the URL is different from SSO_AUTH_SERVER_URL,
    // and that causes failures during token validation
    String ssoUrl = ssoUrlBase.toString().replace(":443", "") + "auth";

    System.setProperty("SSO_AUTH_SERVER_URL", ssoUrl);
    Configuration baseline = JsonSerialization.readValue(configStream, Configuration.class, true // system property replacement
    );

    return AuthzClient.create(new Configuration(baseline.getAuthServerUrl(), baseline.getRealm(),
            baseline.getResource(), baseline.getCredentials(), httpClient));
}

From source file:me.vertretungsplan.parser.BaseParser.java

BaseParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) {
    this.scheduleData = scheduleData;
    this.cookieProvider = cookieProvider;
    this.cookieStore = new BasicCookieStore();
    this.colorProvider = new ColorProvider(scheduleData);
    this.encodingDetector = new UniversalDetector(null);

    try {//  ww  w . j av a  2s.com
        KeyStore ks = loadKeyStore();
        MultiTrustManager multiTrustManager = new MultiTrustManager();
        multiTrustManager.addTrustManager(getDefaultTrustManager());
        multiTrustManager.addTrustManager(trustManagerFromKeystore(ks));

        TrustManager[] trustManagers = new TrustManager[] { multiTrustManager };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
        final HostnameVerifier hostnameVerifier;

        if (scheduleData.getData() != null && scheduleData.getData().has(PARAM_SSL_HOSTNAME)) {
            hostnameVerifier = new CustomHostnameVerifier(scheduleData.getData().getString(PARAM_SSL_HOSTNAME));
        } else {
            hostnameVerifier = new DefaultHostnameVerifier();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }, null, hostnameVerifier);

        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
                .build();
        this.executor = Executor.newInstance(httpclient).use(cookieStore);
    } catch (GeneralSecurityException | JSONException | IOException e) {
        throw new RuntimeException(e);
    }
}