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:org.neo4j.drivers.http.driver.HttpDriverTest.java

@Test
public void shouldInitialiseWithCustomHttpClient() {

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(1);//from  www. ja va 2  s.  c  o m
    connectionManager.setDefaultMaxPerRoute(1);

    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();

    Components.setDriver(new HttpDriver(httpClient));

    assertNotNull(Components.driver());

}

From source file:name.martingeisse.trading_game.platform.application.AbstractApplicationModule.java

@Override
protected void configure() {

    // configuration participants
    defineExtensionPoint(ConfigurationParticipant.class);
    extend(ConfigurationParticipant.class, PostgresService.class);

    // game listeners
    defineExtensionPoint(GameEventListener.class);

    // HTTP client
    bind(HttpClient.class)
            .toInstance(HttpClients.custom().setConnectionManager(new BasicHttpClientConnectionManager())
                    .setDefaultCookieStore(new NullCookieStore()).build());

}

From source file:org.dbrane.cloud.util.httpclient.HttpClientHelper.java

/**
 * ?HttpClient/* www. j ava2 s. c  o  m*/
 * 
 * @return
 */
private static CloseableHttpClient getHttpClient() {
    init();
    return HttpClients.custom().setConnectionManager(cm).build();
}

From source file:securitytools.common.http.HttpClientFactory.java

public static CloseableHttpClient build(ClientConfiguration clientConfiguration)
        throws NoSuchAlgorithmException {
    HttpClientBuilder builder = HttpClients.custom();

    // Certificate Validation
    if (clientConfiguration.isCertificateValidationEnabled()) {
        builder.setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER));
    } else {/*w  w  w  . j a  v a  2  s  . com*/
        // Disable
        builder.setSSLSocketFactory(new TrustingSSLConnectionSocketFactory());
    }

    // Timeouts
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setConnectionRequestTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(clientConfiguration.getSocketTimeout());
    builder.setDefaultRequestConfig(requestConfigBuilder.build());

    // User Agent
    builder.setUserAgent(clientConfiguration.getUserAgent());

    // Proxy
    if (clientConfiguration.getProxyHost() != null) {
        builder.setProxy(clientConfiguration.getProxyHost());
    }

    return builder.build();
}

From source file:de.intevation.irix.ImageClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param imageUrl The url to send the request to.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./*from  www. j  av a  2s. c om*/
 *
 * @throws IOException if communication with print service failed.
 * @throws ImageException if the print job failed.
 */
public static byte[] getImage(String imageUrl, int timeout) throws IOException, ImageException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpGet get = new HttpGet(imageUrl);
    CloseableHttpResponse resp = client.execute(get);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new ImageException(new String(retval));
        } else {
            throw new ImageException("Communication with print service '" + imageUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:com.netflix.spinnaker.orca.pipeline.util.HttpClientUtils.java

private static CloseableHttpClient httpClientWithServiceUnavailableRetryStrategy() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                @Override/*  w w  w  .jav a  2 s .  c  o m*/
                public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    HttpUriRequest currentReq = (HttpUriRequest) context
                            .getAttribute(HttpCoreContext.HTTP_REQUEST);
                    LOGGER.info("Response code {} for {}", statusCode, currentReq.getURI());

                    if (statusCode >= HttpStatus.SC_OK && statusCode <= 299) {
                        return false;
                    }

                    boolean shouldRetry = (statusCode == 429
                            || RETRYABLE_500_HTTP_STATUS_CODES.contains(statusCode))
                            && executionCount <= MAX_RETRIES;
                    if (!shouldRetry) {
                        throw new RetryRequestException(String.format("Not retrying %s. Count %d, Max %d",
                                currentReq.getURI(), executionCount, MAX_RETRIES));
                    }

                    LOGGER.error("Retrying request on response status {}. Count {} Max is {}", statusCode,
                            executionCount, MAX_RETRIES);
                    return true;
                }

                @Override
                public long getRetryInterval() {
                    return RETRY_INTERVAL;
                }
            });

    httpClientBuilder.setRetryHandler((exception, executionCount, context) -> {
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        Uninterruptibles.sleepUninterruptibly(RETRY_INTERVAL, TimeUnit.MILLISECONDS);
        LOGGER.info("Encountered network error. Retrying request {},  Count {} Max is {}", currentReq.getURI(),
                executionCount, MAX_RETRIES);
        return executionCount <= MAX_RETRIES;
    });

    httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_MILLIS)
            .setConnectTimeout(TIMEOUT_MILLIS).setSocketTimeout(TIMEOUT_MILLIS).build());

    return httpClientBuilder.build();
}

From source file:org.eclipse.rdf4j.http.client.util.HttpClientBuilders.java

/**
 * Return an {@link HttpClientBuilder} that can be used to build an {@link HttpClient} which trusts all
 * certificates (particularly including self-signed certificates).
 * /*from  w w  w .ja va  2 s.  c om*/
 * @return a {@link HttpClientBuilder} for <i>SSL trust all</i>
 */
public static HttpClientBuilder getSSLTrustAllHttpClientBuilder() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });

        HostnameVerifier hostNameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(), hostNameVerifier);

        return HttpClients.custom().setSSLSocketFactory(sslSF).useSystemProperties();
    } catch (Exception e) {
        // key management exception, etc.
        throw new RuntimeException(e);
    }
}

From source file:org.mobicents.servlet.restcomm.http.CustomHttpClientBuilder.java

public static HttpClient build(MainConfigurationSet config) {
    SslMode mode = config.getSslMode();/*from  w ww.  j av  a  2 s  .co m*/
    int timeoutConnection = config.getResponseTimeout();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutConnection)
            .setConnectionRequestTimeout(timeoutConnection).setSocketTimeout(timeoutConnection)
            .setCookieSpec(CookieSpecs.STANDARD).build();
    if (mode == SslMode.strict) {
        return HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    } else {
        return buildAllowallClient(requestConfig);
    }
}

From source file:org.springframework.social.openidconnect.api.impl.GAECompatibleClientHttpRequestFactorySelector.java

public static ClientHttpRequestFactory getRequestFactory() {
    Properties properties = System.getProperties();
    String proxyHost = properties.getProperty("http.proxyHost");
    int proxyPort = properties.containsKey("http.proxyPort")
            ? Integer.valueOf(properties.getProperty("http.proxyPort"))
            : 80;/* w  w w  .  j  av a 2  s . c  o m*/
    if (HTTP_COMPONENTS_AVAILABLE) {
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        if (proxyHost != null) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpClientBuilder.setProxy(proxy);
        }
        return HttpComponentsClientRequestFactoryCreator.createRequestFactory(httpClientBuilder.build(),
                proxyHost, proxyPort);
    } else {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        if (proxyHost != null) {
            requestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
        }
        return requestFactory;
    }
}

From source file:de.jlo.talendcomp.tac.TACConnection.java

public void init() {
    client = HttpClients.custom().build();
}