org.apache.http.conn.socket.ConnectionSocketFactory Java Examples

The following examples show how to use org.apache.http.conn.socket.ConnectionSocketFactory. 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: SmartRestTemplateConfig.java    From smart-admin with MIT License 7 votes vote down vote up
@Bean
public HttpClient httpClient() {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", SSLConnectionSocketFactory.getSocketFactory())
            .build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(maxTotal);
    connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .build();
    return HttpClientBuilder.create()
            .setDefaultRequestConfig(requestConfig)
            .setConnectionManager(connectionManager)
            .build();
}
 
Example #2
Source File: HttpUtils.java    From ScriptSpider with Apache License 2.0 6 votes vote down vote up
/**
 * 创建httpclient连接池,并初始化httpclient
 */
public void init() {
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
                new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslsf)
                .build();
        httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // Increase max total connection to 200
        httpClientConnectionManager.setMaxTotal(maxTotalPool);
        // Increase default max connection per route to 20
        httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
        httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
    } catch (Exception e) {

    }
}
 
Example #3
Source File: HttpClientPool.java    From FATE-Serving with Apache License 2.0 6 votes vote down vote up
public static void initPool() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                Dict.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(
                Dict.HTTPS, sslsf).build();
        poolConnManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        poolConnManager.setMaxTotal(500);
        poolConnManager.setDefaultMaxPerRoute(200);
        int socketTimeout = 10000;
        int connectTimeout = 10000;
        int connectionRequestTimeout = 10000;
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                connectTimeout).build();
        httpClient = getConnection();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        logger.error("init http client pool failed:", ex);
    }
}
 
Example #4
Source File: HttpClientServiceImpl.java    From smockin with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient noSslHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

        final SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (x509CertChain, authType) -> true)
                .build();

        return HttpClientBuilder.create()
                .setSSLContext(sslContext)
                .setConnectionManager(
                        new PoolingHttpClientConnectionManager(
                                RegistryBuilder.<ConnectionSocketFactory>create()
                                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                                        .register("https", new SSLConnectionSocketFactory(sslContext,
                                                NoopHostnameVerifier.INSTANCE))
                                        .build()
                        ))
                .build();
    }
 
Example #5
Source File: HttpProtocolParent.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createHttpClient(String hostname, int port) {
	ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
	LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
	Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
			.register("http", plainsf).register("https", sslsf).build();
	PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
	// 将最大连接数增加
	cm.setMaxTotal(maxTotal);
	// 将每个路由基础的连接增加
	cm.setDefaultMaxPerRoute(maxPerRoute);
	HttpHost httpHost = new HttpHost(hostname, port);
	// 将目标主机的最大连接数增加
	cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
	// 请求重试处理
	return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build();
}
 
Example #6
Source File: AbstractNotifierConfig.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Gets an HTTP client that can be used to make requests.
 *
 * @return HTTP client
 */
public CloseableHttpClient getHttpClient(boolean ignoreSSL) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    if (ignoreSSL) {
        final SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (x509CertChain, authType) -> true)
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                        .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
                        .build()
        );
        return HttpClientBuilder.create()
                .setSSLContext(sslContext)
                .setConnectionManager(connectionManager)
                .build();
    }
    return HttpClients.createDefault();
}
 
Example #7
Source File: AbstractHttpClient.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
/**
 * custom http client for server with SSL errors
 *
 * @return
 */
public final CloseableHttpClient getCustomClient() {
    try {
        HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
        builder.setSSLContext(sslContext);
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        builder.setConnectionManager(connMgr);
        return builder.build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
    return getSystemClient();
}
 
Example #8
Source File: ApacheHttpClient.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
public HttpClientConnectionManager create(ApacheHttpClient.DefaultBuilder configuration,
                                          AttributeMap standardOptions) {
    ConnectionSocketFactory sslsf = getPreferredSocketFactory(configuration, standardOptions);

    PoolingHttpClientConnectionManager cm = new
            PoolingHttpClientConnectionManager(
            createSocketFactoryRegistry(sslsf),
            null,
            DefaultSchemePortResolver.INSTANCE,
            null,
            standardOptions.get(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE).toMillis(),
            TimeUnit.MILLISECONDS);

    cm.setDefaultMaxPerRoute(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
    cm.setMaxTotal(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
    cm.setDefaultSocketConfig(buildSocketConfig(standardOptions));

    return cm;
}
 
Example #9
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 #10
Source File: ClientConnection.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static PoolingHttpClientConnectionManager getConnctionManager(){

        Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
        try {
            SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                        new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                        new TrustAllHostNameVerifier());
            socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory> create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", trustSelfSignedSocketFactory)
                    .build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            Data.logger.warn("", e);
        }
        
        PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? 
                new PoolingHttpClientConnectionManager(socketFactoryRegistry):
                new PoolingHttpClientConnectionManager();
        
        // twitter specific options
        cm.setMaxTotal(2000);
        cm.setDefaultMaxPerRoute(200);
        
        return cm;
    }
 
Example #11
Source File: ApacheConnectionManagerFactory.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
private Registry<ConnectionSocketFactory> createSocketFactoryRegistry(ConnectionSocketFactory sslSocketFactory) {

        /*
         * If SSL cert checking for endpoints has been explicitly disabled,
         * register a new scheme for HTTPS that won't cause self-signed certs to
         * error out.
         */
        if (SDKGlobalConfiguration.isCertCheckingDisabled()) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("SSL Certificate checking for endpoints has been " +
                        "explicitly disabled.");
            }
            sslSocketFactory = new TrustingSocketFactory();
        }

        return RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
    }
 
Example #12
Source File: HttpClientBuilder.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException {
    try
    {
        KeyStore keyStore = KeyStoreUtil.createDockerKeyStore(certPath);

        SSLContext sslContext =
                SSLContexts.custom()
                           .setProtocol(SSLConnectionSocketFactory.TLS)
                           .loadKeyMaterial(keyStore, "docker".toCharArray())
                           .loadTrustMaterial(keyStore, null)
                           .build();
        String tlsVerify = System.getenv("DOCKER_TLS_VERIFY");
        SSLConnectionSocketFactory sslsf =
                tlsVerify != null && !tlsVerify.equals("0") && !tlsVerify.equals("false") ?
                        new SSLConnectionSocketFactory(sslContext) :
                        new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        return RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
    }
    catch (GeneralSecurityException e) {
        // this isn't ideal but the net effect is the same
        throw new IOException(e);
    }
}
 
Example #13
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
public void testSSL() throws IOException {

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

        schemeRegistry.register("https", new SSLConnectionSocketFactory(new DavGatewaySSLSocketFactory(),
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()));

        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(schemeRegistry.build());
        HttpClientBuilder clientBuilder = HttpClientBuilder.create()
                .disableRedirectHandling()
                .setConnectionManager(poolingHttpClientConnectionManager);
        try (CloseableHttpClient httpClient = clientBuilder.build()) {

            HttpGet httpget = new HttpGet("https://outlook.office365.com");
            try (CloseableHttpResponse response = httpClient.execute(httpget)) {
                assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode());
            }
        }
    }
 
Example #14
Source File: HttpClientWrapper.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
public static void enabledSSL() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(100);
    client = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .setConnectionManager(cm)
            .build();
}
 
Example #15
Source File: UnixHttpClient.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Ctor.
 * @param socketFile Unix socket on disk.
 */
UnixHttpClient(final File socketFile) {
    this(() -> {
        final PoolingHttpClientConnectionManager pool =
            new PoolingHttpClientConnectionManager(
                RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("unix", new UnixSocketFactory(socketFile))
                    .build()
            );
        pool.setDefaultMaxPerRoute(10);
        pool.setMaxTotal(10);
        return HttpClientBuilder.create()
            .setConnectionManager(pool)
            .addInterceptorFirst(new UserAgentRequestHeader())
            .build();
    });
}
 
Example #16
Source File: IgnoreSSLUtils.java    From MixPush with Apache License 2.0 5 votes vote down vote up
/**
 * for ignoring verify SSL
 */
public static CloseableHttpClient createClient() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslcontext = createIgnoreVerifySSL();

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

    return HttpClients.custom().setConnectionManager(connManager).build();
}
 
Example #17
Source File: AvaticaCommonsHttpClientSpnegoImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Override protected void configureConnectionPool(Registry<ConnectionSocketFactory> registry) {
  super.configureConnectionPool(registry);
  //For backwards compatibility, override the standard values if set
  final String maxCnxns =
      System.getProperty(CACHED_CONNECTIONS_MAX_KEY);
  if (maxCnxns != null) {
    pool.setMaxTotal(Integer.parseInt(maxCnxns));
  }
  //For backwards compatibility, override the standard values if set
  final String maxCnxnsPerRoute = System.getProperty(CACHED_CONNECTIONS_MAX_PER_ROUTE_KEY);
  if (maxCnxnsPerRoute != null) {
    pool.setDefaultMaxPerRoute(Integer.parseInt(maxCnxnsPerRoute));
  }
}
 
Example #18
Source File: AvaticaCommonsHttpClientImplSocketFactoryTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
<T> void verifyFactoryInstance(AvaticaCommonsHttpClientImpl client,
    String registry, Class<T> expected) {
  ConnectionSocketFactory factory = client.socketFactoryRegistry.lookup(registry);
  if (expected == null) {
    assertTrue("Factory for registry " + registry + " expected as null", factory == null);
  } else {
    assertTrue("Factory for registry " + registry + " expected of type " + expected.getName(),
            expected.equals(factory.getClass()));
  }
}
 
Example #19
Source File: HttpConnectionPoolBuilder.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
public PoolingHttpClientConnectionManager createConnectionManager(final Registry<ConnectionSocketFactory> registry) {
    if(log.isDebugEnabled()) {
        log.debug(String.format("Setup connection pool with registry %s", registry));
    }
    final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry);
    manager.setMaxTotal(preferences.getInteger("http.connections.total"));
    manager.setDefaultMaxPerRoute(preferences.getInteger("http.connections.route"));
    // Detect connections that have become stale (half-closed) while kept inactive in the pool
    manager.setValidateAfterInactivity(preferences.getInteger("http.connections.stale.check.ms"));
    return manager;
}
 
Example #20
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
protected void configureHttpsRegistry(RegistryBuilder<ConnectionSocketFactory> registryBuilder) {
  try {
    SSLContext sslContext = getSSLContext();
    final HostnameVerifier verifier = getHostnameVerifier(hostnameVerification);
    SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext, verifier);
    registryBuilder.register("https", sslFactory);
  } catch (Exception e) {
    LOG.error("HTTPS registry configuration failed");
    throw new RuntimeException(e);
  }
}
 
Example #21
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
protected Registry<ConnectionSocketFactory> configureSocketFactories() {
  RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  if (host.getSchemeName().equalsIgnoreCase("https")) {
    configureHttpsRegistry(registryBuilder);
  } else {
    configureHttpRegistry(registryBuilder);
  }
  return registryBuilder.build();
}
 
Example #22
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public void testBasicAuthentication() throws IOException {
    Settings.setLoggingLevel("org.apache.http", Level.DEBUG);

    RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();
    schemeRegistry.register("https", new SSLConnectionSocketFactory(new DavGatewaySSLSocketFactory(),
            SSLConnectionSocketFactory.getDefaultHostnameVerifier()));

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
            = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(AuthScope.ANY, credentials);

    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(schemeRegistry.build());
    HttpClientBuilder clientBuilder = HttpClientBuilder.create()
            .disableRedirectHandling()
            .setDefaultCredentialsProvider(provider)
            .setConnectionManager(poolingHttpClientConnectionManager);
    try (CloseableHttpClient httpClient = clientBuilder.build()) {

        HttpGet httpget = new HttpGet("https://outlook.office365.com/EWS/Exchange.asmx");
        try (CloseableHttpResponse response = httpClient.execute(httpget)) {
            assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
            String responseString = new BasicResponseHandler().handleResponse(response);
            System.out.println(responseString);
        }
    }
}
 
Example #23
Source File: InsecurePilosaClientIT.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Registry<ConnectionSocketFactory> getRegistry() {
    HostnameVerifier verifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostName, SSLSession session) {
            return true;
        }
    };

    SSLContext sslContext = null;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        e.printStackTrace();
    }
    if (sslContext == null) {
        throw new RuntimeException("SSL Context not created");
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContext,
            new String[]{"TLSv1.2"}, null, verifier);
    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();
}
 
Example #24
Source File: TomHttpClientGenerator.java    From tom-crawler with Apache License 2.0 5 votes vote down vote up
public TomHttpClientGenerator() {
    Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", buildSSLConnectionSocketFactory())
            .build();
    connectionManager = new PoolingHttpClientConnectionManager(reg);
    connectionManager.setDefaultMaxPerRoute(100);
}
 
Example #25
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
protected void configureConnectionPool(Registry<ConnectionSocketFactory> registry) {
  pool = new PoolingHttpClientConnectionManager(registry);
  // Increase max total connection to 100
  final String maxCnxns =
      System.getProperty(MAX_POOLED_CONNECTIONS_KEY,
          MAX_POOLED_CONNECTIONS_DEFAULT);
  pool.setMaxTotal(Integer.parseInt(maxCnxns));
  // Increase default max connection per route to 25
  final String maxCnxnsPerRoute = System.getProperty(MAX_POOLED_CONNECTION_PER_ROUTE_KEY,
      MAX_POOLED_CONNECTION_PER_ROUTE_DEFAULT);
  pool.setDefaultMaxPerRoute(Integer.parseInt(maxCnxnsPerRoute));
}
 
Example #26
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static HttpClient createDefaultHttpClient() {
	Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory())
			.register("https", SSLConnectionSocketFactory.getSocketFactory())
			.build();

	PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(schemeRegistry);
	connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
	connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

	return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}
 
Example #27
Source File: HttpPoolClient.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
public  HttpClientConnectionManager createHttpClientConnectionManager() {
	SSLContext sslContext = null;
	try {
		sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
			@Override
			public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				return false;
			}
		}).build();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
			NoopHostnameVerifier.INSTANCE);
	Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory)
			.build();
	PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
			socketFactoryRegistry);
	// 最大连接数
	poolingHttpClientConnectionManager.setMaxTotal(httpClientConfig.getMaxTotal());
	// 单个站点最大连接数
	poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientConfig.getMaxPerRoute());
	// 长连接
	poolingHttpClientConnectionManager.setDefaultSocketConfig(
			SocketConfig.custom().setSoTimeout(httpClientConfig.getSocketTimeout()).setSoKeepAlive(true).build());
	// 连接不活跃多久检查毫秒 并不是100 % 可信
	poolingHttpClientConnectionManager.setValidateAfterInactivity(httpClientConfig.getValidateAfterInactivity());
	// 空闲扫描线程
	HttpClientIdleConnectionMonitor.registerConnectionManager(poolingHttpClientConnectionManager, httpClientConfig);
	return poolingHttpClientConnectionManager;
}
 
Example #28
Source File: HttpsFactoryTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCreateIgnoringSslSocketFactory() throws KeyStoreException {
    HttpsConfig httpsConfig = httpsConfigBuilder.verifySslCertificatesOfServices(false).build();
    HttpsFactory httpsFactory = new HttpsFactory(httpsConfig);
    ConnectionSocketFactory socketFactory = httpsFactory.createSslSocketFactory();
    assertEquals(SSLConnectionSocketFactory.class, socketFactory.getClass());
    assertFalse(httpsFactory.getUsedKeyStore().aliases().hasMoreElements());
}
 
Example #29
Source File: HttpsFactoryTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCreateSecureSslSocketFactory() {
    HttpsConfig httpsConfig = httpsConfigBuilder.build();
    HttpsFactory httpsFactory = new HttpsFactory(httpsConfig);
    ConnectionSocketFactory socketFactory = httpsFactory.createSslSocketFactory();
    assertEquals(SSLConnectionSocketFactory.class, socketFactory.getClass());
}
 
Example #30
Source File: HttpsFactory.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
public ConnectionSocketFactory createSslSocketFactory() {
    if (config.isVerifySslCertificatesOfServices()) {
        return createSecureSslSocketFactory();
    } else {
        apimlLog.log("org.zowe.apiml.common.ignoringSsl");
        return createIgnoringSslSocketFactory();
    }
}