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:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare connection/*from  w  w w  .  j  a  v  a 2s  .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:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param client JAX-RS client instance for which the connector is being created.
 * @param config client configuration.//from  ww w . j  av  a2 s . co  m
 */
ApacheConnector(final Client client, final Configuration config) {
    final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);
    if (connectionManager != null) {
        if (!(connectionManager instanceof HttpClientConnectionManager)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.CONNECTION_MANAGER,
                            connectionManager.getClass().getName(),
                            HttpClientConnectionManager.class.getName()));
        }
    }

    Object reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
    if (reqConfig != null) {
        if (!(reqConfig instanceof RequestConfig)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                            reqConfig.getClass().getName(), RequestConfig.class.getName()));
            reqConfig = null;
        }
    }

    final SSLContext sslContext = client.getSslContext();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(client, config, sslContext));
    clientBuilder.setConnectionManagerShared(PropertiesHelper.getValue(config.getProperties(),
            ApacheClientProperties.CONNECTION_MANAGER_SHARED, false, null));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
    if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
        clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
    }

    final Object proxyUri;
    proxyUri = config.getProperty(ClientProperties.PROXY_URI);
    if (proxyUri != null) {
        final URI u = getProxyUri(proxyUri);
        final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
        final String userName;
        userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                String.class);
        if (userName != null) {
            final String password;
            password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                    String.class);

            if (password != null) {
                final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                        new UsernamePasswordCredentials(userName, password));
                clientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        clientBuilder.setProxy(proxy);
    }

    final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
            .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
    this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;

    final boolean ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
            ApacheClientProperties.DISABLE_COOKIES);

    if (reqConfig != null) {
        final RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);

    /* DK_CLD: Add our connection reuse strategy. */
    clientBuilder.setConnectionReuseStrategy(new UpgradeAwareConnectionReuseStrategy());
    clientBuilder.setRequestExecutor(new HttpRequestExecutor() {
        protected HttpResponse doReceiveResponse(final HttpRequest request,
                final org.apache.http.HttpClientConnection conn, final HttpContext context)
                throws HttpException, IOException {
            Args.notNull(request, "HTTP request");
            Args.notNull(conn, "Client connection");
            Args.notNull(context, "HTTP context");
            HttpResponse response = null;
            int statusCode = 0;

            while (response == null || (statusCode < HttpStatus.SC_OK
                    // DK_CLD: the original implementation provided this loop to retry the HTTP request as long as
                    // an intermediate response is returned (1xx status). This is however not suitable for the
                    // status code 101 returned from Docker (and more generally, WebSockets) to notify that the
                    // connection has been upgraded to raw TCP streaming. In such case the server ultimate response
                    // is not HTTP anymore.
                    && statusCode != HttpStatus.SC_SWITCHING_PROTOCOLS)) {

                response = conn.receiveResponseHeader();
                if (canResponseHaveBody(request, response)) {
                    conn.receiveResponseEntity(response);
                }
                statusCode = response.getStatusLine().getStatusCode();

            } // while intermediate response

            return response;
        }

        @Override
        protected boolean canResponseHaveBody(HttpRequest request, HttpResponse response) {
            boolean canResponseHaveBody = super.canResponseHaveBody(request, response);
            return canResponseHaveBody
                    || response.getStatusLine().getStatusCode() == HttpStatus.SC_SWITCHING_PROTOCOLS;
        }
    });

    this.client = clientBuilder.build();
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param client JAX-RS client instance for which the connector is being created.
 * @param config client configuration.//  w ww  . j a  v  a2 s.com
 */
ApacheConnector(final Client client, final Configuration config) {
    final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);
    if (connectionManager != null) {
        if (!(connectionManager instanceof HttpClientConnectionManager)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.CONNECTION_MANAGER,
                            connectionManager.getClass().getName(),
                            HttpClientConnectionManager.class.getName()));
        }
    }

    Object reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
    if (reqConfig != null) {
        if (!(reqConfig instanceof RequestConfig)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                            reqConfig.getClass().getName(), RequestConfig.class.getName()));
            reqConfig = null;
        }
    }

    final SSLContext sslContext = client.getSslContext();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(client, config, sslContext));
    clientBuilder.setConnectionManagerShared(PropertiesHelper.getValue(config.getProperties(),
            ApacheClientProperties.CONNECTION_MANAGER_SHARED, false, null));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
    if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
        clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
    }

    final Object retryHandler = config.getProperties().get(ApacheClientProperties.RETRY_HANDLER);
    if (retryHandler != null && (retryHandler instanceof HttpRequestRetryHandler)) {
        clientBuilder.setRetryHandler((HttpRequestRetryHandler) retryHandler);
    }

    final Object proxyUri;
    proxyUri = config.getProperty(ClientProperties.PROXY_URI);
    if (proxyUri != null) {
        final URI u = getProxyUri(proxyUri);
        final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
        final String userName;
        userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                String.class);
        if (userName != null) {
            final String password;
            password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                    String.class);

            if (password != null) {
                final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                        new UsernamePasswordCredentials(userName, password));
                clientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        clientBuilder.setProxy(proxy);
    }

    final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
            .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
    this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;

    final boolean ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
            ApacheClientProperties.DISABLE_COOKIES);

    if (reqConfig != null) {
        final RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);
    this.client = clientBuilder.build();
}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param config client configuration./*from w w  w .  j  a  v  a  2 s.c o m*/
 */
ApacheConnector(Configuration config) {
    Object reqConfig = null;

    if (config != null) {
        final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);

        if (connectionManager != null) {
            if (!(connectionManager instanceof HttpClientConnectionManager)) {
                LOGGER.log(Level.WARNING, LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(
                        ApacheClientProperties.CONNECTION_MANAGER, connectionManager.getClass().getName(),
                        HttpClientConnectionManager.class.getName()));
            }
        }

        reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
        if (reqConfig != null) {
            if (!(reqConfig instanceof RequestConfig)) {
                LOGGER.log(Level.WARNING,
                        LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                                reqConfig.getClass().getName(), RequestConfig.class.getName()));
                reqConfig = null;
            }
        }
    }

    final SSLContext sslContext = getSslContext(config);
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(config, sslContext));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    int connectTimeout = 0;
    int socketTimeout = 0;
    boolean ignoreCookies = false;
    if (config != null) {
        connectTimeout = ClientProperties.getValue(config.getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
        socketTimeout = ClientProperties.getValue(config.getProperties(), ClientProperties.READ_TIMEOUT, 0);
        ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
                ApacheClientProperties.DISABLE_COOKIES);

        final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
        if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
            clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
        }

        Object proxyUri;
        proxyUri = config.getProperty(ClientProperties.PROXY_URI);
        if (proxyUri != null) {
            final URI u = getProxyUri(proxyUri);
            final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
            String userName;
            userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                    String.class);
            if (userName != null) {
                String password;
                password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                        String.class);

                if (password != null) {
                    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                            new UsernamePasswordCredentials(userName, password));
                    clientBuilder.setDefaultCredentialsProvider(credsProvider);
                }
            }
            clientBuilder.setProxy(proxy);
        }

        final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
                .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
        this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;
    } else {
        this.preemptiveBasicAuth = false;
    }

    if (reqConfig != null) {
        RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (connectTimeout > 0) {
            reqConfigBuilder.setConnectTimeout(connectTimeout);
        }
        if (socketTimeout > 0) {
            reqConfigBuilder.setSocketTimeout(socketTimeout);
        }
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        requestConfigBuilder.setConnectTimeout(connectTimeout);
        requestConfigBuilder.setSocketTimeout(socketTimeout);
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);
    this.client = clientBuilder.build();
}

From source file:crawlercommons.fetcher.http.SimpleHttpFetcher.java

private void init() {
    if (_httpClient == null) {
        synchronized (SimpleHttpFetcher.class) {
            if (_httpClient != null)
                return;

            final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

            // Set the socket and connection timeout to be something
            // reasonable.
            requestConfigBuilder.setSocketTimeout(_socketTimeout);
            requestConfigBuilder.setConnectTimeout(_connectionTimeout);
            requestConfigBuilder.setConnectionRequestTimeout(_connectionRequestTimeout);

            /*/*from  w  w  w.  j  av  a2 s .  c  o m*/
             * CoreConnectionPNames.TCP_NODELAY='http.tcp.nodelay':
             * determines whether Nagle's algorithm is to be used. Nagle's
             * algorithm tries to conserve bandwidth by minimizing the
             * number of segments that are sent. When applications wish to
             * decrease network latency and increase performance, they can
             * disable Nagle's algorithm (that is enable TCP_NODELAY. Data
             * will be sent earlier, at the cost of an increase in bandwidth
             * consumption. This parameter expects a value of type
             * java.lang.Boolean. If this parameter is not set, TCP_NODELAY
             * will be enabled (no delay).
             */
            // FIXME Could not find this parameter in http-client version
            // 4.5
            // HttpConnectionParams.setTcpNoDelay(params, true);
            // HttpProtocolParams.setVersion(params, _httpVersion);

            httpClientBuilder.setUserAgent(_userAgent.getUserAgentString());

            // HttpProtocolParams.setContentCharset(params, "UTF-8");
            // HttpProtocolParams.setHttpElementCharset(params, "UTF-8");

            /*
             * CoreProtocolPNames.USE_EXPECT_CONTINUE=
             * 'http.protocol.expect-continue': activates the Expect:
             * 100-Continue handshake for the entity enclosing methods. The
             * purpose of the Expect: 100-Continue handshake is to allow the
             * client that is sending a request message with a request body
             * to determine if the origin server is willing to accept the
             * request (based on the request headers) before the client
             * sends the request body. The use of the Expect: 100-continue
             * handshake can result in a noticeable performance improvement
             * for entity enclosing requests (such as POST and PUT) that
             * require the target server's authentication. The Expect:
             * 100-continue handshake should be used with caution, as it may
             * cause problems with HTTP servers and proxies that do not
             * support HTTP/1.1 protocol. This parameter expects a value of
             * type java.lang.Boolean. If this parameter is not set,
             * HttpClient will not attempt to use the handshake.
             */
            requestConfigBuilder.setExpectContinueEnabled(true);

            /*
             * CoreProtocolPNames.WAIT_FOR_CONTINUE=
             * 'http.protocol.wait-for-continue': defines the maximum period
             * of time in milliseconds the client should spend waiting for a
             * 100-continue response. This parameter expects a value of type
             * java.lang.Integer. If this parameter is not set HttpClient
             * will wait 3 seconds for a confirmation before resuming the
             * transmission of the request body.
             */
            // FIXME Could not find this parameter in http-client version
            // 4.5
            // params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE,
            // 5000);

            // FIXME Could not find this parameter in http-client version
            // 4.5
            // CookieSpecParamBean cookieParams = new
            // CookieSpecParamBean(params);
            // cookieParams.setSingleHeader(false);

            // Create and initialize connection socket factory registry
            RegistryBuilder<ConnectionSocketFactory> registry = RegistryBuilder
                    .<ConnectionSocketFactory>create();
            registry.register("http", PlainConnectionSocketFactory.getSocketFactory());
            SSLConnectionSocketFactory sf = createSSLConnectionSocketFactory();
            if (sf != null) {
                registry.register("https", sf);
            } else {
                LOGGER.warn("No valid SSLContext found for https");
            }

            _connectionManager = new PoolingHttpClientConnectionManager(registry.build());
            _connectionManager.setMaxTotal(_maxThreads);
            _connectionManager.setDefaultMaxPerRoute(getMaxConnectionsPerHost());

            /*
             * CoreConnectionPNames.STALE_CONNECTION_CHECK=
             * 'http.connection.stalecheck': determines whether stale
             * connection check is to be used. Disabling stale connection
             * check may result in a noticeable performance improvement (the
             * check can cause up to 30 millisecond overhead per request) at
             * the risk of getting an I/O error when executing a request
             * over a connection that has been closed at the server side.
             * This parameter expects a value of type java.lang.Boolean. For
             * performance critical operations the check should be disabled.
             * If this parameter is not set, the stale connection check will
             * be performed before each request execution.
             * 
             * We don't need I/O exceptions in case if Server doesn't
             * support Kee-Alive option; our client by default always tries
             * keep-alive.
             */
            // Even with stale checking enabled, a connection can "go stale"
            // between the check and the next request. So we still need to
            // handle the case of a closed socket (from the server side),
            // and disabling this check improves performance.
            // Stale connections will be checked in a separate monitor
            // thread
            _connectionManager.setValidateAfterInactivity(-1);

            httpClientBuilder.setConnectionManager(_connectionManager);
            httpClientBuilder.setRetryHandler(new MyRequestRetryHandler(_maxRetryCount));
            httpClientBuilder.setRedirectStrategy(new MyRedirectStrategy(getRedirectMode()));
            httpClientBuilder.setRequestExecutor(new MyHttpRequestExecutor());

            // FUTURE KKr - support authentication
            // FIXME Could not find this parameter in http-client version
            // 4.5
            // HttpClientParams.setAuthenticating(params, false);

            requestConfigBuilder.setCookieSpec(CookieSpecs.DEFAULT);

            if (getMaxRedirects() == 0) {
                requestConfigBuilder.setRedirectsEnabled(false);
            } else {
                requestConfigBuilder.setRedirectsEnabled(true);
                requestConfigBuilder.setMaxRedirects(getMaxRedirects());
            }

            // Set up default headers. This helps us get back from servers
            // what we want.
            HashSet<Header> defaultHeaders = new HashSet<Header>();
            defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, getAcceptLanguage()));
            defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET));
            defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, DEFAULT_ACCEPT_ENCODING));
            defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, DEFAULT_ACCEPT));

            httpClientBuilder.setDefaultHeaders(defaultHeaders);

            httpClientBuilder.setKeepAliveStrategy(new MyConnectionKeepAliveStrategy());

            monitor = new IdleConnectionMonitorThread(_connectionManager);
            monitor.start();

            httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
            _httpClient = httpClientBuilder.build();
        }
    }

}

From source file:org.apache.hadoop.hbase.thrift2.client.ThriftConnection.java

public synchronized HttpClient getHttpClient() {
    if (httpClient != null) {
        return httpClient;
    }/*w  w w  . jav a 2  s.c  o m*/
    int retry = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
            HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
    long pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE, 5);
    HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(getOperationTimeout());
    builder.setRetryHandler(new DelayRetryHandler(retry, pause));
    builder.setDefaultRequestConfig(requestBuilder.build());
    httpClient = builder.build();
    httpClientCreated = true;
    return httpClient;
}

From source file:org.apache.marmotta.client.util.HTTPUtil.java

public static HttpClient createClient(ClientConfiguration config, String context) {

    final HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setUserAgent("Marmotta Client Library/" + MetaUtil.getVersion());
    httpClientBuilder.setRedirectStrategy(new MarmottaRedirectStrategy());
    httpClientBuilder.setRetryHandler(new MarmottaHttpRequestRetryHandler());

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setSocketTimeout(config.getSoTimeout());
    requestConfigBuilder.setConnectTimeout(config.getConnectionTimeout());
    requestConfigBuilder.setRedirectsEnabled(true);
    requestConfigBuilder.setMaxRedirects(3);
    httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    if (config.getConectionManager() != null) {
        httpClientBuilder.setConnectionManager(config.getConectionManager());
    } else {//from w w w .ja  va  2  s  .c  o  m
        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                //.register("https", )
                .build();

        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(100);
        httpClientBuilder.setConnectionManager(cm);
    }

    return httpClientBuilder.build();
}

From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java

private static HttpClient buildSpengoHttpClient() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
    builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
        @Override/* ww  w. j  av a2s.  c om*/
        public Principal getUserPrincipal() {
            return null;
        }

        @Override
        public String getPassword() {
            return null;
        }
    });
    builder.setDefaultCredentialsProvider(credentialsProvider);

    // Avoid output WARN: Cookie rejected
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    builder.setDefaultRequestConfig(globalConfig);

    CloseableHttpClient httpClient = builder.build();

    return httpClient;
}