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

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

Introduction

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

Prototype

public final HttpClientBuilder setDefaultRequestConfig(final RequestConfig config) 

Source Link

Document

Assigns default RequestConfig instance which will be used for request execution if not explicitly set in the client execution context.

Usage

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private static CloseableHttpClient createHttpClient(KeyManager km, TrustManager tm) throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

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

    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(km != null ? new KeyManager[] { km } : null, tm != null ? new TrustManager[] { tm } : null,
            new SecureRandom());

    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    sfr.register("https", sf);

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();

    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);/*from   w ww . ja  va2s  .c o m*/
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

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

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

    return cb.build();
}

From source file:com.microsoft.azure.keyvault.authentication.BearerAuthenticationSetup.java

/**
 * Configures a {@link HttpClientBuilder} to call the informed
 * {@link BearerCredentialsSupport} object to answer "bearer" challenges,
 * such as <code>401 Unauthorized</code> responses. The
 * {@link BearerCredentialsSupport} object can return a token an hide
 * <code>401</code> results from users.
 *///from   w  w  w .j  a v  a  2s  .  com
public static void configureClientBuilder(HttpClientBuilder httpBuilder, BearerCredentialsSupport support) {
    // Configure to use "bearer" as preferred authentication scheme (without
    // this, the client uses basic, diggest, etc).
    Builder configBuilder = RequestConfig.custom()
            .setTargetPreferredAuthSchemes(Arrays.asList(new String[] { BearerAuthentication.NAME }));
    httpBuilder.setDefaultRequestConfig(configBuilder.build());

    // Provide a custom "bearer" authentication provider.
    RegistryBuilder<AuthSchemeProvider> schemeProviderBuilder = RegistryBuilder.create();
    schemeProviderBuilder.register(BearerAuthentication.NAME, BearerAuthenticationProvider.INSTANCE);
    httpBuilder.setDefaultAuthSchemeRegistry(schemeProviderBuilder.build());

    // Configure to use the CloudCredentialsProvider.
    httpBuilder.setDefaultCredentialsProvider(new BearerCredentialsProvider(support));
}

From source file:org.coding.git.api.CodingNetConnection.java

@NotNull
private static CloseableHttpClient createClient(@NotNull CodingNetAuthData auth) {
    HttpClientBuilder builder = HttpClients.custom();

    return builder.setDefaultRequestConfig(createRequestConfig(auth))
            .setDefaultConnectionConfig(createConnectionConfig(auth))
            //.setDefaultCredentialsProvider(createCredentialsProvider(auth))
            .setDefaultHeaders(createHeaders(auth)).addInterceptorFirst(PREEMPTIVE_BASIC_AUTH)
            .setSslcontext(CertificateManager.getInstance().getSslContext())
            //--cookie
            .setDefaultCookieStore(createCookieStore(auth))
            .setHostnameVerifier((X509HostnameVerifier) CertificateManager.HOSTNAME_VERIFIER).build();
}

From source file:org.jboss.as.test.http.util.TestHttpClientUtils.java

/**
 * Same as {@link TestHttpClientUtils#promiscuousCookieHttpClient()} but instead returns a builder that can be further configured.
 *
 * @return {@link HttpClientBuilder} of the http client that gives free cookies to everybody
 * @see TestHttpClientUtils#promiscuousCookieHttpClient()
 *//*  w w  w.  j  a va2  s .c o  m*/
public static HttpClientBuilder promiscuousCookieHttpClientBuilder() {
    HttpClientBuilder builder = HttpClients.custom();

    RegistryBuilder<CookieSpecProvider> registryBuilder = CookieSpecRegistries.createDefaultBuilder();
    Registry<CookieSpecProvider> promiscuousCookieSpecRegistry = registryBuilder
            .register("promiscuous", new PromiscuousCookieSpecProvider()).build();
    builder.setDefaultCookieSpecRegistry(promiscuousCookieSpecRegistry);

    RequestConfig requestConfig = RequestConfig.custom().setCookieSpec("promiscuous").build();
    builder.setDefaultRequestConfig(requestConfig);

    builder.setDefaultCookieStore(new PromiscuousCookieStore());

    return builder;
}

From source file:com.liferay.sync.engine.lan.session.LanSession.java

private static HttpClient _createHttpClient(int connectTimeout, int maxPerRoute, int maxTotal,
        int socketTimeout) {

    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();

    try {//from  w  w w  .  ja v  a 2  s  . c  o  m
        registryBuilder.register("https", _getSSLSocketFactory());
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);
    }

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            registryBuilder.build());

    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    connectionManager.setMaxTotal(maxTotal);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    RequestConfig.Builder builder = RequestConfig.custom();

    builder.setConnectTimeout(connectTimeout);
    builder.setSocketTimeout(socketTimeout);

    httpClientBuilder.setDefaultRequestConfig(builder.build());

    httpClientBuilder.setConnectionManager(connectionManager);

    return httpClientBuilder.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 {// www.  ja v a 2s  .  c o m
        // 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:org.kontalk.client.DownloadClient.java

private static CloseableHttpClient createHTTPClient(PrivateKey privateKey, X509Certificate certificate,
        boolean validateCertificate) {
    //HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    HttpClientBuilder clientBuilder = HttpClients.custom();
    try {/*from   www  . j  ava  2  s  .c  om*/
        SSLContext sslContext = TrustUtils.getCustomSSLContext(privateKey, certificate, validateCertificate);
        clientBuilder.setSslcontext(sslContext);
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
            | KeyManagementException | UnrecoverableKeyException | NoSuchProviderException ex) {
        LOGGER.log(Level.WARNING, "unable to set SSL context", ex);
        return null;
    }

    RequestConfig.Builder rcBuilder = RequestConfig.custom();
    // handle redirects :)
    rcBuilder.setRedirectsEnabled(true);
    // HttpClient bug caused by Lighttpd
    rcBuilder.setExpectContinueEnabled(false);
    clientBuilder.setDefaultRequestConfig(rcBuilder.build());

    // create connection manager
    //ClientConnectionManager connMgr = new SingleClientConnManager(params, registry);

    //return new DefaultHttpClient(connMgr, params);
    return clientBuilder.build();
}

From source file:org.ligoj.app.http.security.RestAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) {
    final String userpassword = StringUtils.defaultString(authentication.getCredentials().toString(), "");
    final String userName = StringUtils.lowerCase(authentication.getPrincipal().toString());

    // First get the cookie
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());
    final HttpPost httpPost = new HttpPost(getSsoPostUrl());

    // Do the POST
    try (CloseableHttpClient httpClient = clientBuilder.build()) {
        final String content = String.format(getSsoPostContent(), userName, userpassword);
        httpPost.setEntity(new StringEntity(content, StandardCharsets.UTF_8));
        httpPost.setHeader("Content-Type", "application/json");
        final HttpResponse httpResponse = httpClient.execute(httpPost);
        if (HttpStatus.SC_NO_CONTENT == httpResponse.getStatusLine().getStatusCode()) {
            // Succeed authentication, save the cookies data inside the authentication
            return newAuthentication(userName, userpassword, authentication, httpResponse);
        }//from   w  w  w. jav  a  2s.  co  m
        log.info("Failed authentication of {}[{}] : {}", userName, userpassword.length(),
                httpResponse.getStatusLine().getStatusCode());
        httpResponse.getEntity().getContent().close();
    } catch (final IOException e) {
        log.warn("Remote SSO server is not available", e);
    }
    throw new BadCredentialsException("Invalid user or password");
}

From source file:org.ligoj.app.http.security.DigestAuthenticationFilter.java

@Override
public Authentication attemptAuthentication(final HttpServletRequest request,
        final HttpServletResponse response) {
    final String token = request.getParameter("token");

    if (token != null) {
        // Token is the last part of URL

        // First get the cookie
        final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
        clientBuilder.setDefaultRequestConfig(
                RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build());

        // Do the POST
        try (CloseableHttpClient httpClient = clientBuilder.build()) {
            final HttpPost httpPost = new HttpPost(getSsoPostUrl());
            httpPost.setEntity(new StringEntity(token, StandardCharsets.UTF_8.name()));
            httpPost.setHeader("Content-Type", "application/json");
            final HttpResponse httpResponse = httpClient.execute(httpPost);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(
                        EntityUtils.toString(httpResponse.getEntity()), "N/A", new ArrayList<>()));
            }//  ww w . j  a  va 2 s  .  co  m
        } catch (final IOException e) {
            log.warn("Local SSO server is not available", e);
        }

    }
    throw new BadCredentialsException("Invalid user or password");
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtil.java

private static HttpClientBuilder setupBuilder(HttpClientBuilder builder, SolrParams config) {

    Builder requestConfigBuilder = RequestConfig.custom()
            .setRedirectsEnabled(config.getBool(HttpClientUtil.PROP_FOLLOW_REDIRECTS, false))
            .setDecompressionEnabled(false)
            .setConnectTimeout(config.getInt(HttpClientUtil.PROP_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT))
            .setSocketTimeout(config.getInt(HttpClientUtil.PROP_SO_TIMEOUT, DEFAULT_SO_TIMEOUT));

    String cpolicy = cookiePolicy;
    if (cpolicy != null) {
        requestConfigBuilder.setCookieSpec(cpolicy);
    }/*from w  ww  . jav  a 2s.  co m*/

    RequestConfig requestConfig = requestConfigBuilder.build();

    HttpClientBuilder retBuilder = builder.setDefaultRequestConfig(requestConfig);

    if (config.getBool(HttpClientUtil.PROP_USE_RETRY, true)) {
        retBuilder = retBuilder.setRetryHandler(new SolrHttpRequestRetryHandler(3));

    } else {
        retBuilder = retBuilder.setRetryHandler(NO_RETRY);
    }

    final String basicAuthUser = config.get(HttpClientUtil.PROP_BASIC_AUTH_USER);
    final String basicAuthPass = config.get(HttpClientUtil.PROP_BASIC_AUTH_PASS);

    if (basicAuthUser != null && basicAuthPass != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(basicAuthUser, basicAuthPass));
        retBuilder.setDefaultCredentialsProvider(credsProvider);
    }

    if (config.getBool(HttpClientUtil.PROP_ALLOW_COMPRESSION, false)) {
        retBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
        retBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
    } else {
        retBuilder.disableContentCompression();
    }

    return retBuilder;
}