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

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

Introduction

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

Prototype

public final HttpClientBuilder setDefaultSocketConfig(final SocketConfig config) 

Source Link

Document

Assigns default SocketConfig .

Usage

From source file:com.nextdoor.bender.ipc.http.AbstractHttpTransportFactory.java

protected HttpClientBuilder getClientBuilder(boolean useSSL, String url, Map<String, String> stringHeaders,
        int socketTimeout) {

    HttpClientBuilder cb = HttpClientBuilder.create();

    /*/* w w  w.  j  a v  a2 s  .c o  m*/
     * Setup SSL
     */
    if (useSSL) {
        /*
         * All trusting SSL context
         */
        try {
            cb.setSSLContext(getSSLContext());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        /*
         * All trusting hostname verifier
         */
        cb.setSSLHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    }

    /*
     * Add default headers
     */
    ArrayList<BasicHeader> headers = new ArrayList<BasicHeader>(stringHeaders.size());
    stringHeaders.forEach((k, v) -> headers.add(new BasicHeader(k, v)));
    cb.setDefaultHeaders(headers);

    /*
     * Set socket timeout and transport threads
     */
    SocketConfig sc = SocketConfig.custom().setSoTimeout(socketTimeout).build();
    cb.setDefaultSocketConfig(sc);
    cb.setMaxConnPerRoute(this.config.getThreads());
    cb.setMaxConnTotal(this.config.getThreads());

    return cb;
}

From source file:de.codecentric.elasticsearch.plugin.kerberosrealm.AbstractUnitTest.java

protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final HttpClientBuilder hcb = HttpClients.custom();

    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);//  new NegotiateSchemeProvider();
        final Credentials jaasCreds = new JaasCredentials();
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM),
                new NTCredentials("Guest", "Guest", "Guest", "Guest"));
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

        hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }//from ww  w  .  ja v  a 2s  .  com

    hcb.setDefaultCredentialsProvider(credsProvider);
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
    final CloseableHttpClient httpClient = hcb.build();
    return httpClient;
}

From source file:com.gs.tools.doc.extractor.core.DownloadManager.java

private DownloadManager() {
    logger.info("Init DownloadManager");
    cookieStore = new BasicCookieStore();
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultCookieStore(cookieStore);

    Collection<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Accept",
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate,sdch"));
    headers.add(new BasicHeader("Accept-Language", "en-US,en;q=0.8"));
    //        headers.add(new BasicHeader("Accept-Encoding", 
    //                "gzip,deflate,sdch"));
    clientBuilder.setDefaultHeaders(headers);

    ConnectionConfig.Builder connectionConfigBuilder = ConnectionConfig.custom();
    connectionConfigBuilder.setBufferSize(10485760);
    clientBuilder.setDefaultConnectionConfig(connectionConfigBuilder.build());

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoKeepAlive(true);
    socketConfigBuilder.setSoTimeout(3000000);
    clientBuilder.setDefaultSocketConfig(socketConfigBuilder.build());
    logger.info("Create HTTP Client");
    httpClient = clientBuilder.build();/* w w  w . j a  v  a  2s .co  m*/

}

From source file:lucee.runtime.tag.Http.java

public static void setTimeout(HttpClientBuilder builder, TimeSpan timeout) {
    if (timeout == null || timeout.getMillis() <= 0)
        return;//ww  w. j  av a  2s .  co  m

    int ms = (int) timeout.getMillis();
    if (ms < 0)
        ms = Integer.MAX_VALUE;

    // builder.setConnectionTimeToLive(ms, TimeUnit.MILLISECONDS);
    SocketConfig sc = SocketConfig.custom().setSoTimeout(ms).build();
    builder.setDefaultSocketConfig(sc);
}

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare asynchronous connection.//from ww w. j a va 2s  . c o  m
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException
 */
public void prepareAsyncConnection() throws EWSHttpException {
    try {
        //ssl config
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);
        builder.setSchemePortResolver(new DefaultSchemePortResolver());

        EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger);
        builder.setSSLSocketFactory(factory);
        builder.setSslcontext(factory.getContext());

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new NTCredentials(getUserName(), getPassword(), "", getDomain()));
        builder.setDefaultCredentialsProvider(credsProvider);

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        ArrayList<String> authPrefs = new ArrayList<String>();
        authPrefs.add(AuthSchemes.NTLM);
        rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        //

        builder.setDefaultRequestConfig(rcBuilder.build());

        //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects
        //create the client and execute requests
        client = builder.build();
        httpPostReq = new HttpPost(getUrl().toString());
        response = client.execute(httpPostReq);
    } catch (IOException e) {
        client = null;
        httpPostReq = null;
        throw new EWSHttpException("Unable to open connection to " + this.getUrl());
    } catch (Exception e) {
        client = null;
        httpPostReq = null;
        e.printStackTrace();
        throw new EWSHttpException("SSL problem " + this.getUrl());
    }
}

From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java

protected final CloseableHttpClient getHTTPClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHTTPClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(truststore)),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(keystore)),
                "changeit".toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }// w w w.  java  2  s.c  o m

        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}

From source file:com.floragunn.searchguard.ssl.AbstractUnitTest.java

protected final CloseableHttpClient getHTTPClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHTTPClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("truststore.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("node-0-keystore.jks")),
                "changeit".toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }//from   w  ww  . j  a v  a 2  s.  c o m

        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}

From source file:com.xebialabs.overthere.winrm.WinRmClient.java

private void configureHttpClient(final HttpClientBuilder httpclient) throws GeneralSecurityException {
    configureTrust(httpclient);// w  w  w .j  a v  a  2 s  . co  m
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    httpclient.setDefaultCredentialsProvider(credentialsProvider);

    configureAuthentication(credentialsProvider, BASIC, new BasicUserPrincipal(username));

    if (enableKerberos) {
        String spnServiceClass = kerberosUseHttpSpn ? "HTTP" : "WSMAN";
        RegistryBuilder<AuthSchemeProvider> authSchemeRegistryBuilder = RegistryBuilder.create();
        authSchemeRegistryBuilder.register(KERBEROS, new WsmanKerberosSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        authSchemeRegistryBuilder.register(SPNEGO, new WsmanSPNegoSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        httpclient.setDefaultAuthSchemeRegistry(authSchemeRegistryBuilder.build());
        configureAuthentication(credentialsProvider, KERBEROS, new KerberosPrincipal(username));
        configureAuthentication(credentialsProvider, SPNEGO, new KerberosPrincipal(username));
    }

    httpclient.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build());
    httpclient.setDefaultRequestConfig(
            RequestConfig.custom().setAuthenticationEnabled(true).setConnectTimeout(connectionTimeout).build());
}

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare connection/*w w  w. java  2  s .  com*/
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException the eWS http exception
 */
@Override
public void prepareConnection() throws EWSHttpException {
    try {
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        if (getProxy() != null) {
            HttpHost proxy = new HttpHost(getProxy().getHost(), getProxy().getPort());
            builder.setProxy(proxy);

            if (HttpProxyCredentials.isProxySet()) {
                NTCredentials cred = new NTCredentials(HttpProxyCredentials.getUserName(),
                        HttpProxyCredentials.getPassword(), "", HttpProxyCredentials.getDomain());
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxy), cred);
                builder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        if (getUserName() != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(getUserName(), getPassword(), "", getDomain()));
            builder.setDefaultCredentialsProvider(credsProvider);
        }

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setAuthenticationEnabled(true);
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setRedirectsEnabled(isAllowAutoRedirect());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        if (getUserName() != null) {
            ArrayList<String> authPrefs = new ArrayList<String>();
            authPrefs.add(AuthSchemes.NTLM);
            rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        }
        //
        builder.setDefaultRequestConfig(rcBuilder.build());

        httpPostReq = new HttpPost(getUrl().toString());
        httpPostReq.addHeader("Content-type", getContentType());
        //httpPostReq.setDoAuthentication(true);
        httpPostReq.addHeader("User-Agent", getUserAgent());
        httpPostReq.addHeader("Accept", getAccept());
        httpPostReq.addHeader("Keep-Alive", "300");
        httpPostReq.addHeader("Connection", "Keep-Alive");

        if (isAcceptGzipEncoding()) {
            httpPostReq.addHeader("Accept-Encoding", "gzip,deflate");
        }

        if (getHeaders().size() > 0) {
            for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) {
                httpPostReq.addHeader(httpHeader.getKey(), httpHeader.getValue());
            }
        }

        //create the client
        client = builder.build();
    } catch (Exception er) {
        er.printStackTrace();
    }
}

From source file:com.floragunn.searchguard.AbstractUnitTest.java

protected final CloseableHttpClient getHTTPClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHTTPClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("truststore.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath(keystore)),
                "changeit".toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }/* w w  w  . j a va 2 s . co  m*/

        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}