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.hp.autonomy.hod.client.HodServiceConfigFactory.java

public static HodServiceConfig<EntityType.Application, TokenType.Simple> getHodServiceConfig(
        final TokenProxyService<EntityType.Application, TokenType.Simple> tokenProxyService,
        final Endpoint endpoint) {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.disableCookieManagement();/* w ww  . j av  a  2  s. c om*/
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60000).build());

    final String proxyHost = System.getProperty("hp.hod.https.proxyHost");

    if (proxyHost != null) {
        final Integer proxyPort = Integer.valueOf(System.getProperty("hp.hod.https.proxyPort", "8080"));
        builder.setProxy(new HttpHost(proxyHost, proxyPort));
    }

    final HodServiceConfig.Builder<EntityType.Application, TokenType.Simple> configBuilder = new HodServiceConfig.Builder<EntityType.Application, TokenType.Simple>(
            endpoint.getUrl()).setHttpClient(builder.build());

    if (tokenProxyService != null) {
        configBuilder.setTokenProxyService(tokenProxyService);
    }

    return configBuilder.build();
}

From source file:com.github.caldav4j.functional.support.CalDavFixture.java

private static HttpClient configureHttpClient(final CaldavCredential credential) {
    // HttpClient 4 requires a Cred providers, to be added during creation of client
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(credential.user, credential.password));

    // Default Host setting
    HttpRoutePlanner routePlanner = new DefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE) {

        @Override/*  w  w  w  .  j  ava2  s .  c  om*/
        public HttpRoute determineRoute(final HttpHost target, final HttpRequest request,
                final HttpContext context) throws HttpException {
            return super.determineRoute(
                    target != null ? target
                            : new HttpHost(credential.host, credential.port, credential.protocol),
                    request, context);
        }

    };

    HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setRoutePlanner(routePlanner);

    if (credential.getProxyHost() != null) {
        builder.setProxy(new HttpHost(credential.getProxyHost(),
                (credential.getProxyPort() > 0) ? credential.getProxyPort() : 8080));
    }

    return builder.build();
}

From source file:emea.summit.architects.HackathlonAPIResource.java

private static String getRequest(String url, String contentType) throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    HttpUriRequest get = new HttpGet(url);
    get.setHeader("Content-Type", contentType);

    HttpResponse response = client.execute(get);
    StatusLine status = response.getStatusLine();
    String content = EntityUtils.toString(response.getEntity());
    //JSONObject json = new JSONObject(content);

    return content;
}

From source file:emea.summit.architects.HackathlonAPIResource.java

private static String putRequest(String url, String contentType) throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    HttpUriRequest put = new HttpPut(url);
    put.setHeader("Content-Type", contentType);

    HttpResponse response = client.execute(put);
    StatusLine status = response.getStatusLine();
    String content = EntityUtils.toString(response.getEntity());
    //JSONObject json = new JSONObject(content);

    return content;
}

From source file:emea.summit.architects.HackathlonAPIResource.java

private static String postRequest(String url, String contentType, HttpEntity entity) throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", contentType);
    post.setEntity(entity);//w  w  w. j  a va  2 s. com

    HttpResponse response = client.execute(post);
    StatusLine status = response.getStatusLine();
    String content = EntityUtils.toString(response.getEntity());
    //JSONObject json = new JSONObject(content);

    return content;
}

From source file:com.angelmmg90.consumerservicespotify.configuration.SpringWebConfig.java

@Bean
public static RestTemplate getTemplate() throws IOException {
    if (template == null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
                new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));

        Header[] h = new Header[3];
        h[0] = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        h[1] = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + ACCESS_TOKEN);

        List<Header> headers = new ArrayList<>(Arrays.asList(h));

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.useSystemProperties();
        clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        clientBuilder.setDefaultHeaders(headers).build();
        String SAMPLE_URL = "https://api.spotify.com/v1/users/yourUserName/playlists/7HHFd1tNiIFIwYwva5MTNv";

        HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();

        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        CloseableHttpClient client = clientBuilder.build();
        client.execute(request);//from w w w.j a  v  a  2  s.co  m

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(client);

        template = new RestTemplate();
        template.setRequestFactory(factory);
    }

    return template;
}

From source file:lh.api.showcase.server.util.HttpClientUtils.java

public static CloseableHttpClient createHttpClient(HasProxySettings proxySetting,
        PoolingHttpClientConnectionManager connectionManager) {
    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e475

    HttpClientBuilder clientBuilder = HttpClients.custom();
    if (proxySetting != null && proxySetting.isActive()) {
        logger.info("Set the http proxy (" + proxySetting.getHost() + ":" + proxySetting.getPort() + ")");
        CredentialsProvider credsProvider = Preconditions.checkNotNull(proxySetting.getCredentialsProvider());
        HttpHost proxy = new HttpHost(proxySetting.getHost(), proxySetting.getPort());
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

        clientBuilder.setRoutePlanner(routePlanner).setDefaultCredentialsProvider(credsProvider);
    }//ww  w. j  a  v  a2 s  . c  o m
    if (connectionManager != null) {
        clientBuilder.setConnectionManager(connectionManager);
    }
    return clientBuilder.build();
}

From source file:org.springframework.cloud.deployer.admin.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates./*from  w  ww .j  a v a 2  s.  c  o  m*/
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    restTemplate.setRequestFactory(requestFactory);
}

From source file:org.springframework.cloud.dataflow.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates./* w w  w  . j ava2  s. c  om*/
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, URI host, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpHost targetHost = new HttpHost(host.getHost(), host.getPort(), host.getScheme());

    final HttpComponentsClientHttpRequestFactory requestFactory = new PreemptiveBasicAuthHttpComponentsClientHttpRequestFactory(
            httpClient, targetHost);
    restTemplate.setRequestFactory(requestFactory);
}

From source file:com.moviejukebox.tools.YamjHttpClientBuilder.java

@SuppressWarnings("resource")
private static YamjHttpClient buildHttpClient() {
    LOG.trace("Create new YAMJ http client");

    // create proxy
    HttpHost proxy = null;/* w w  w  .j a va2s  .  c om*/
    CredentialsProvider credentialsProvider = null;

    if (StringUtils.isNotBlank(PROXY_HOST) && PROXY_PORT > 0) {
        proxy = new HttpHost(PROXY_HOST, PROXY_PORT);

        if (StringUtils.isNotBlank(PROXY_USERNAME) && StringUtils.isNotBlank(PROXY_PASSWORD)) {
            credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
                    new UsernamePasswordCredentials(PROXY_USERNAME, PROXY_PASSWORD));
        }
    }

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(TIMEOUT_SOCKET).build());
    connManager.setMaxTotal(20);
    connManager.setDefaultMaxPerRoute(2);

    CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(1000).setMaxObjectSize(8192).build();

    HttpClientBuilder builder = CachingHttpClientBuilder.create().setCacheConfig(cacheConfig)
            .setConnectionManager(connManager).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_READ)
                    .setConnectTimeout(TIMEOUT_CONNECT).setSocketTimeout(TIMEOUT_SOCKET)
                    .setCookieSpec(CookieSpecs.IGNORE_COOKIES).setProxy(proxy).build());

    // show status
    showStatus();

    // build the client
    YamjHttpClient wrapper = new YamjHttpClient(builder.build(), connManager);
    wrapper.setUserAgentSelector(new WebBrowserUserAgentSelector());
    wrapper.addGroupLimit(".*", 1); // default limit, can be overwritten

    // First we have to read/create the rules
    String maxDownloadSlots = PropertiesUtil.getProperty("mjb.MaxDownloadSlots");
    if (StringUtils.isNotBlank(maxDownloadSlots)) {
        LOG.debug("Using download limits: {}", maxDownloadSlots);

        Pattern pattern = Pattern.compile(",?\\s*([^=]+)=(\\d+)");
        Matcher matcher = pattern.matcher(maxDownloadSlots);
        while (matcher.find()) {
            String group = matcher.group(1);
            try {
                final Integer maxResults = Integer.valueOf(matcher.group(2));
                wrapper.addGroupLimit(group, maxResults);
                LOG.trace("Added download slot '{}' with max results {}", group, maxResults);
            } catch (NumberFormatException error) {
                LOG.debug("Rule '{}' is no valid regexp, ignored", group);
            }
        }
    }

    return wrapper;
}