Java Code Examples for org.apache.http.impl.conn.PoolingHttpClientConnectionManager#setDefaultConnectionConfig()

The following examples show how to use org.apache.http.impl.conn.PoolingHttpClientConnectionManager#setDefaultConnectionConfig() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApacheConnectionManagerFactory.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public HttpClientConnectionManager create(final HttpClientSettings settings) {
    ConnectionSocketFactory sslsf = getPreferredSocketFactory(settings);

    final PoolingHttpClientConnectionManager cm = new
            PoolingHttpClientConnectionManager(
            createSocketFactoryRegistry(sslsf),
            null,
            DefaultSchemePortResolver.INSTANCE,
            new DelegatingDnsResolver(settings.getDnsResolver()),
            settings.getConnectionPoolTTL(),
            TimeUnit.MILLISECONDS);

    cm.setValidateAfterInactivity(settings.getValidateAfterInactivityMillis());
    cm.setDefaultMaxPerRoute(settings.getMaxConnections());
    cm.setMaxTotal(settings.getMaxConnections());
    cm.setDefaultSocketConfig(buildSocketConfig(settings));
    cm.setDefaultConnectionConfig(buildConnectionConfig(settings));

    return cm;
}
 
Example 2
Source File: ClickHouseHttpClientBuilder.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
private PoolingHttpClientConnectionManager getConnectionManager()
    throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    RegistryBuilder<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory());

    if (properties.getSsl()) {
        HostnameVerifier verifier = "strict".equals(properties.getSslMode()) ? SSLConnectionSocketFactory.getDefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE;
        registry.register("https", new SSLConnectionSocketFactory(getSSLContext(), verifier));
    }

    //noinspection resource
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
        registry.build(),
        null,
        null,
        new IpVersionPriorityResolver(),
        properties.getTimeToLiveMillis(),
        TimeUnit.MILLISECONDS
    );

    connectionManager.setDefaultMaxPerRoute(properties.getDefaultMaxPerRoute());
    connectionManager.setMaxTotal(properties.getMaxTotal());
    connectionManager.setDefaultConnectionConfig(getConnectionConfig());
    return connectionManager;
}
 
Example 3
Source File: HttpClientPool.java    From message_interface with MIT License 5 votes vote down vote up
private static CloseableHttpClient client() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(100);
    cm.setMaxTotal(400);

    MessageConstraints messageConstraints = MessageConstraints.custom()
            .setMaxHeaderCount(200)
            .setMaxLineLength(2000)
            .build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints)
            .build();

    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(5000)
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000)
            .build();

    cm.setDefaultConnectionConfig(connectionConfig);

    return HttpClients.custom()
            .setConnectionManager(cm)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();
}
 
Example 4
Source File: HttpUtils.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 创建 HttpClient 连接池.
 */
private PoolingHttpClientConnectionManager createHttpClientConnPool(ConnectionConfig connectionConfig) {
    PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
            RegistryBuilder.<ConnectionSocketFactory>create().
                    register("http", PlainConnectionSocketFactory.getSocketFactory()).
                    register("https", buildSSLConn()).build());
    httpClientConnectionManager.setMaxTotal(MAX_TOTAL); // 设置连接池线程最大数量
    httpClientConnectionManager.setDefaultMaxPerRoute(MAX_ROUTE_TOTAL); // 设置单个路由最大的连接线程数量
    httpClientConnectionManager.setDefaultConnectionConfig(connectionConfig);
    return httpClientConnectionManager;
}
 
Example 5
Source File: HttpClientUtil.java    From feiqu-opensource with Apache License 2.0 4 votes vote down vote up
private static void init() {
    try {
        SSLContext sslContext =
                SSLContexts.custom()
                        .loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()), new TrustStrategy() {
                            @Override
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }
                        }).build();
        SSLConnectionSocketFactory sslSFactory =
                new SSLConnectionSocketFactory(sslContext);
        Registry<ConnectionSocketFactory> socketFactoryRegistry =
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslSFactory)
                        .build();

        PoolingHttpClientConnectionManager connManager =
                new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(CommonConstant.TIMEOUT).setTcpNoDelay(true).build();
        connManager.setDefaultSocketConfig(socketConfig);

        ConnectionConfig connectionConfig =
                ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE)
                        .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).build();
        connManager.setDefaultConnectionConfig(connectionConfig);
        connManager.setMaxTotal(500);
        connManager.setDefaultMaxPerRoute(300);
        HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount > 2) {
                    return false;
                }
                if (exception instanceof InterruptedIOException) {
                    return true;
                }
                if (exception instanceof ConnectTimeoutException) {
                    return true;
                }
                if (exception instanceof UnknownHostException) {
                    return true;
                }
                if (exception instanceof SSLException) {
                    return true;
                }
                HttpRequest request = HttpClientContext.adapt(context).getRequest();
                if (!(request instanceof HttpEntityEnclosingRequest)) {
                    return true;
                }
                return false;
            }
        };
        HttpClientBuilder httpClientBuilder =
                HttpClients.custom().setConnectionManager(connManager)
                        .setRetryHandler(retryHandler)
                        .setDefaultCookieStore(new BasicCookieStore()).setUserAgent(userAgent);
        if (proxy != null) {
            httpClientBuilder.setRoutePlanner(new DefaultProxyRoutePlanner(proxy)).build();
        }
        httpClient = httpClientBuilder.build();

        requestConfig = RequestConfig.custom().setSocketTimeout(CommonConstant.TIMEOUT).
                setConnectTimeout(CommonConstant.TIMEOUT).
                setConnectionRequestTimeout(CommonConstant.TIMEOUT).
                setCookieSpec(CookieSpecs.STANDARD).
                build();
    } catch (Exception e) {
        logger.error("Exception:", e);
    }
}
 
Example 6
Source File: HttpSyncClient.java    From Almost-Famous with MIT License 4 votes vote down vote up
public CloseableHttpClient createSyncClient(boolean proxy)
        throws Exception {

    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory();
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    SSLContext sslcontext = SSLContexts.createSystemDefault();

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

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom()
            .setTcpNoDelay(true)
            .build();
    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);
    // Validate connections after 1 sec of inactivity
    connManager.setValidateAfterInactivity(1000);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom()
            .setMaxHeaderCount(200)
            .setMaxLineLength(2000)
            .build();
    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints)
            .build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    connManager.setDefaultConnectionConfig(connectionConfig);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(poolSize);
    if (maxPerRoute > 0) {
        connManager.setDefaultMaxPerRoute(maxPerRoute);
    } else {
        connManager.setDefaultMaxPerRoute(10);
    }

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .build();

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();

    return httpclient;
}