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:com.insys.cfclient.nozzle.InfluxDBSender.java

@PostConstruct
public void postConstruct() throws Exception {
    if (properties.isSkipSslValidation()) {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy).build();

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

        CloseableHttpClient apacheHttpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

        requestFactory.setHttpClient(apacheHttpClient);

        this.httpClient.setRequestFactory(requestFactory);
    }/*  w w  w .j a  va  2s  .  c  o m*/
}

From source file:com.redhat.developers.msa.namaste.NamasteResource.java

/**
 * This is were the "magic" happens: it creates a Feign, which is a proxy interface for remote calling a REST endpoint with
 * Hystrix fallback support.//from   w w w  .j a v  a2 s  .c o  m
 *
 * @return The feign pointing to the service URL and with Hystrix fallback.
 */
private OlaService getNextService() {
    final String serviceName = "ola";
    final Brave brave = new Brave.Builder("namaste").spanCollector(HttpSpanCollector
            .create(System.getenv("ZIPKIN_SERVER_URL"), new EmptySpanCollectorMetricsHandler())).build();
    // This stores the Original/Parent ServerSpan from ZiPkin.
    final ServerSpan serverSpan = brave.serverSpanThreadBinder().getCurrentServerSpan();
    final CloseableHttpClient httpclient = HttpClients.custom()
            .addInterceptorFirst(new BraveHttpRequestInterceptor(brave.clientRequestInterceptor(),
                    new DefaultSpanNameProvider()))
            .addInterceptorFirst(new BraveHttpResponseInterceptor(brave.clientResponseInterceptor())).build();
    String url = String.format("http://%s:8080/", serviceName);
    return HystrixFeign.builder()
            // Use apache HttpClient which contains the ZipKin Interceptors
            .client(new ApacheHttpClient(httpclient))
            // Bind Zipkin Server Span to Feign Thread
            .requestInterceptor((t) -> brave.serverSpanThreadBinder().setCurrentSpan(serverSpan))
            .logger(new Logger.ErrorLogger()).logLevel(Level.BASIC).decoder(new JacksonDecoder())
            .target(OlaService.class, url, () -> Collections.singletonList("Ola response (fallback)"));
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(FilterConfig filterConfig) {
    HttpClientBuilder builder = null;//from  ww w.jav  a  2s .  c o m
    GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext()
            .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) {
        GatewayServices services = (GatewayServices) filterConfig.getServletContext()
                .getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
        MetricsService metricsService = services.getService(GatewayServices.METRICS_SERVICE);
        builder = metricsService.getInstrumented(HttpClientBuilder.class);
    } else {
        builder = HttpClients.custom();
    }
    if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UseJaasCredentials());

        Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true)).build();

        builder = builder.setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCookieStore(new HadoopAuthCookieStore())
                .setDefaultCredentialsProvider(credentialsProvider);
    } else {
        builder = builder.setDefaultCookieStore(new NoCookieStore());
    }

    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    builder.setRedirectStrategy(new NeverRedirectStrategy());
    builder.setRetryHandler(new NeverRetryHandler());

    int maxConnections = getMaxConnections(filterConfig);
    builder.setMaxConnTotal(maxConnections);
    builder.setMaxConnPerRoute(maxConnections);

    builder.setDefaultRequestConfig(getRequestConfig(filterConfig));

    HttpClient client = builder.build();
    return client;
}

From source file:com.redhat.developers.msa.hola.HolaResource.java

/**
 * This is were the "magic" happens: it creates a Feign, which is a proxy interface for remote calling a REST endpoint with
 * Hystrix fallback support./*w  w w . j a v a2s.co  m*/
 *
 * @return The feign pointing to the service URL and with Hystrix fallback.
 */
private AlohaService getNextService() {
    final String serviceName = "aloha";
    // This stores the Original/Parent ServerSpan from ZiPkin.
    final ServerSpan serverSpan = brave.serverSpanThreadBinder().getCurrentServerSpan();
    final CloseableHttpClient httpclient = HttpClients.custom()
            .addInterceptorFirst(new BraveHttpRequestInterceptor(brave.clientRequestInterceptor(),
                    new DefaultSpanNameProvider()))
            .addInterceptorFirst(new BraveHttpResponseInterceptor(brave.clientResponseInterceptor())).build();
    String url = String.format("http://%s:8080/", serviceName);
    return HystrixFeign.builder()
            // Use apache HttpClient which contains the ZipKin Interceptors
            .client(new ApacheHttpClient(httpclient))
            // Bind Zipkin Server Span to Feign Thread
            .requestInterceptor((t) -> brave.serverSpanThreadBinder().setCurrentSpan(serverSpan))
            .logger(new Logger.ErrorLogger()).logLevel(Level.BASIC).decoder(new JacksonDecoder())
            .target(AlohaService.class, url, () -> Collections.singletonList("Aloha response (fallback)"));
}

From source file:org.wso2.carbon.identity.cloud.web.jaggery.clients.MutualSSLHttpClient.java

public MutualSSLHttpClient() {
    String filePath = null;//ww  w  .j  a  va  2 s.co m
    try {
        final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        filePath = ServerConfiguration.getInstance().getFirstProperty(SecurityKeyStoreLocation);
        InputStream keystoreInput = new FileInputStream(new File(filePath));
        keyStore.load(keystoreInput,
                ServerConfiguration.getInstance().getFirstProperty(SecurityKeyStorePassword).toCharArray());

        final KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        filePath = ServerConfiguration.getInstance().getFirstProperty(SecurityTrustStoreLocation);
        InputStream truststoreInput = new FileInputStream(new File(filePath));
        trustStore.load(truststoreInput,
                ServerConfiguration.getInstance().getFirstProperty(SecurityTrustStorePassword).toCharArray());

        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).loadKeyMaterial(keyStore,
                ServerConfiguration.getInstance().getFirstProperty(SecurityKeyStorePassword).toCharArray())
                .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (KeyStoreException e) {
        log.error("Error while instantiating key store for key store type : " + keyStoreType, e);
    } catch (FileNotFoundException e) {
        log.error("File not found in the given path : " + filePath, e);
    } catch (IOException e) {
        log.error("Error while loading the key store in the given path : " + filePath, e);
    } catch (CertificateException e) {
        log.error("Certificate error in the key store : " + filePath, e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Algorithm error in the key store : " + filePath, e);
    } catch (UnrecoverableKeyException e) {
        log.error("Error while creating the SSLContext", e);
    } catch (KeyManagementException e) {
        log.error("Error while creating the SSLContext", e);
    }
}

From source file:com.joken.notice.message.util.HttpRequestHandler.java

/**
 * ??get//from  ww w  .ja va2s . c  o m
 * @Auther Hanzibin
 * @date 3:18:48 PM,Mar 11, 2016
 * @return String 
 */
public String sendGetRequest() {
    CloseableHttpResponse httpResponse = null;
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setMaxTotal(300);
    connManager.setDefaultMaxPerRoute(20);

    if (requestConfig == null) {
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
                .setStaleConnectionCheckEnabled(true).setConnectTimeout(10000).setSocketTimeout(10000).build();
    }
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager)
            .setDefaultRequestConfig(requestConfig).build();
    HttpGet hp = new HttpGet(url);
    try {
        httpResponse = httpClient.execute(hp);
        if (httpResponse.getStatusLine().getStatusCode() == 200)
            return EntityUtils.toString(httpResponse.getEntity());
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        try {
            hp.releaseConnection();
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:org.ulyssis.ipp.publisher.HttpOutput.java

@Override
public void outputScore(Score score) {
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createSslCustomContext(),
            new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    try (CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build()) {
        HttpPost req = new HttpPost(options.getHttp().toURI());
        byte[] scoreBytes = Serialization.getJsonMapper().writeValueAsBytes(score);
        HttpEntity ent = new ByteArrayEntity(scoreBytes, ContentType.APPLICATION_JSON);
        req.setEntity(ent);/*from   www . j ava  2  s  . c  om*/
        try (CloseableHttpResponse response = httpClient.execute(req)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                LOG.error("Non-success result!");
                return;
            }
            HttpEntity entity = response.getEntity();
            if (entity.getContentLength() != 7L) {
                LOG.error("Non-success result!");
                return;
            }
            String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            if (!"SUCCESS".equals(result)) {
                LOG.error("Non-success result!");
                return;
            }
        }
    } catch (Exception e) {
        // TODO: DO SOMETHING WITH THE EXCEPTION!
        LOG.error("Exception", e);
    }
}

From source file:io.fabric8.maven.docker.access.hc.http.HttpClientBuilder.java

public CloseableHttpClient buildBasicClient() throws IOException {
    return HttpClients.custom().setConnectionManager(getBasicConnectionFactory(certPath)).build();
}

From source file:org.jenkinsci.plugins.kubernetesworkflowsteps.KubeStepExecution.java

private static CloseableHttpClient getClient()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    if (client == null) {
        synchronized (client_lock) {
            if (client == null) {
                SSLContextBuilder builder = SSLContexts.custom();
                builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

                SSLContext sslContext = builder.build();

                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                Collection<BasicHeader> headers = new ArrayList<BasicHeader>();
                headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
                headers.add(new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + env.get("BEARER_TOKEN")));

                client = HttpClients.custom().setDefaultHeaders(headers).setSSLSocketFactory(sslsf).build();
            }/*  w w w  . j av a  2  s  .com*/
        }
    }
    return client;
}