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

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

Introduction

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

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:com.qwazr.utils.http.HttpUtils.java

/**
 * Create a new HttpClient which accept untrusted SSL certificates
 *
 * @return a new HttpClient/* www .  j  av  a  2  s  .  c  o m*/
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static CloseableHttpClient createHttpClient_AcceptsUntrustedCerts()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    final HttpClientBuilder unsecureHttpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    unsecureHttpClientBuilder.setSSLContext(sslContext);

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    unsecureHttpClientBuilder.setConnectionManager(connMgr);
    return unsecureHttpClientBuilder.build();
}

From source file:lucee.commons.net.http.httpclient4.HTTPEngineImpl.java

private static HTTPResponse _invoke(URL url, HttpUriRequest request, String username, String password,
        long timeout, boolean redirect, String charset, String useragent, ProxyData proxy,
        lucee.commons.net.http.Header[] headers, Map<String, String> formfields) throws IOException {

    HttpClientBuilder builder = HttpClients.custom();

    // redirect//from  w  w w.j ava 2s .  c om
    if (redirect)
        builder.setRedirectStrategy(new DefaultRedirectStrategy());
    else
        builder.disableRedirectHandling();

    HttpHost hh = new HttpHost(url.getHost(), url.getPort());
    setHeader(request, headers);
    if (CollectionUtil.isEmpty(formfields))
        setContentType(request, charset);
    setFormFields(request, formfields, charset);
    setUserAgent(request, useragent);
    if (timeout > 0)
        builder.setConnectionTimeToLive(timeout, TimeUnit.MILLISECONDS);
    HttpContext context = setCredentials(builder, hh, username, password, false);
    setProxy(builder, request, proxy);
    CloseableHttpClient client = builder.build();
    if (context == null)
        context = new BasicHttpContext();
    return new HTTPResponse4Impl(url, context, request, client.execute(request, context));
}

From source file:org.dasein.cloud.utils.requester.DaseinParallelRequestExecutor.java

public List<T> execute() throws DaseinRequestException {
    final HttpClientBuilder clientBuilder = setProxyIfRequired(httpClientBuilder);

    final CloseableHttpClient httpClient = clientBuilder.build();

    List<T> results = new ArrayList<T>();
    List<Callable<T>> tasks = new ArrayList<Callable<T>>();
    for (final HttpUriRequest httpUriRequest : httpUriRequests) {
        tasks.add(new Callable<T>() {
            @Override/*from  w ww. ja  v a  2 s . c  o  m*/
            public T call() throws Exception {
                return execute(httpClient, httpUriRequest);
            }
        });
    }

    try {
        try {
            ExecutorService executorService = Executors.newFixedThreadPool(httpUriRequests.size());
            List<Future<T>> futures = executorService.invokeAll(tasks);
            for (Future<T> future : futures) {
                T result = future.get();
                results.add(result);
            }
            return results;
        } finally {
            httpClient.close();
        }
    } catch (Exception e) {
        throw new DaseinRequestException(e.getMessage(), e);
    }
}

From source file:com.fredhopper.core.connector.index.upload.impl.RestTemplateProvider.java

public RestTemplate createTemplate(final String host, final Integer port, final String username,
        final String password) {
    Preconditions.checkArgument(StringUtils.isNotBlank(host));
    Preconditions.checkArgument(port != null);
    Preconditions.checkArgument(StringUtils.isNotBlank(username));
    Preconditions.checkArgument(StringUtils.isNotBlank(password));

    final AuthScope authscope = new AuthScope(host, port.intValue());
    final Credentials credentials = new UsernamePasswordCredentials(username, password);
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authscope, credentials);

    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    final CloseableHttpClient httpClient = clientBuilder.build();

    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}

From source file:com.restfiddle.handler.http.builder.RfHttpClientBuilder.java

public CloseableHttpClient build(RfRequestDTO requestDTO, HttpUriRequest request) {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    //Set Digest Authentication
    digestAuthHandler.setCredentialsProvider(requestDTO, clientBuilder);

    CloseableHttpClient httpClient = clientBuilder.build();
    return httpClient;
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.HttpStreamTest.java

@Test
public void httpFilePostTest() throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpClient client = builder.build();

    URI url = makeURI();/*ww  w . j  a v  a  2  s  . c o m*/
    HttpPost post = new HttpPost(url);

    File file = new File(samplesDir, "/http-file/log.txt");
    EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setFile(file);
    entityBuilder.setContentType(ContentType.TEXT_PLAIN);

    MultipartEntityBuilder builder2 = MultipartEntityBuilder.create();
    builder2.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, "file.ext"); // NON-NLS
    HttpEntity multipart = builder2.build();

    post.setEntity(multipart);

    final HttpResponse returned = client.execute(post);
    assertNotNull(returned);

}

From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java

private static HTTPResponse _invoke(URL url, HttpUriRequest request, String username, String password,
        long timeout, boolean redirect, String charset, String useragent, ProxyData proxy,
        lucee.commons.net.http.Header[] headers, Map<String, String> formfields) throws IOException {

    HttpClientBuilder builder = getHttpClientBuilder();

    // redirect/*  w w  w.j  a va 2s .  c om*/
    if (redirect)
        builder.setRedirectStrategy(new DefaultRedirectStrategy());
    else
        builder.disableRedirectHandling();

    HttpHost hh = new HttpHost(url.getHost(), url.getPort());
    setHeader(request, headers);
    if (CollectionUtil.isEmpty(formfields))
        setContentType(request, charset);
    setFormFields(request, formfields, charset);
    setUserAgent(request, useragent);
    if (timeout > 0)
        Http.setTimeout(builder, TimeSpanImpl.fromMillis(timeout));
    HttpContext context = setCredentials(builder, hh, username, password, false);
    setProxy(builder, request, proxy);
    CloseableHttpClient client = builder.build();
    if (context == null)
        context = new BasicHttpContext();
    return new HTTPResponse4Impl(url, context, request, client.execute(request, context));
}

From source file:org.apache.commons.jcs.auxiliary.remote.http.client.AbstractHttpClient.java

/**
 * Sets the default Properties File and Heading, and creates the HttpClient and connection
 * manager./*from w w  w.  j av  a  2 s .co m*/
 * <p>
 * @param remoteHttpCacheAttributes
 */
public AbstractHttpClient(RemoteHttpCacheAttributes remoteHttpCacheAttributes) {
    this.remoteHttpCacheAttributes = remoteHttpCacheAttributes;

    String httpVersion = getRemoteHttpCacheAttributes().getHttpVersion();
    if ("1.1".equals(httpVersion)) {
        this.httpVersion = HttpVersion.HTTP_1_1;
    } else if ("1.0".equals(httpVersion)) {
        this.httpVersion = HttpVersion.HTTP_1_0;
    } else {
        log.warn("Unrecognized value for 'httpVersion': [" + httpVersion + "], defaulting to 1.1");
        this.httpVersion = HttpVersion.HTTP_1_1;
    }

    HttpClientBuilder builder = HttpClientBuilder.create();
    configureClient(builder);
    this.httpClient = builder.build();
}

From source file:org.eclipse.rdf4j.http.client.SharedHttpClientSessionManager.java

private CloseableHttpClient createHttpClient() {
    HttpClientBuilder nextHttpClientBuilder = httpClientBuilder;
    if (nextHttpClientBuilder != null) {
        return nextHttpClientBuilder.build();
    }/*w  w  w .  j  a  v  a2  s.  co  m*/
    return HttpClientBuilder.create().useSystemProperties().disableAutomaticRetries().build();
}

From source file:com.hp.octane.integrations.services.rest.SSCRestClientImpl.java

SSCRestClientImpl(OctaneSDK.SDKServicesConfigurer configurer) {
    if (configurer == null || configurer.pluginServices == null) {
        throw new IllegalArgumentException("invalid configurer");
    }/*  w w w.j  av a2  s . com*/

    SSLContext sslContext = SSLContexts.createSystemDefault();
    HostnameVerifier hostnameVerifier = new OctaneRestClientImpl.CustomHostnameVerifier();
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_TOTAL_CONNECTIONS);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager);

    httpClient = clientBuilder.build();
}