org.apache.http.config.RegistryBuilder Java Examples

The following examples show how to use org.apache.http.config.RegistryBuilder. 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: MPRestClient.java    From dx-java with MIT License 10 votes vote down vote up
/**
 * Create a HttpClient
 * @return a HttpClient
 */
private HttpClient createHttpClient() {
    SSLContext sslContext = SSLContexts.createDefault();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[]{"TLSv1.1", "TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(MercadoPago.SDK.getMaxConnections());
    connectionManager.setDefaultMaxPerRoute(MercadoPago.SDK.getMaxConnections());
    connectionManager.setValidateAfterInactivity(VALIDATE_INACTIVITY_INTERVAL_MS);

    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MercadoPago.SDK.getRetries(), false);

    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new KeepAliveStrategy())
            .setRetryHandler(retryHandler)
            .disableCookieManagement()
            .disableRedirectHandling();

    return httpClientBuilder.build();
}
 
Example #2
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 #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: 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 #5
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Override public void setUsernamePassword(AuthenticationType authType, String username,
    String password) {
  this.credentials = new UsernamePasswordCredentials(
      Objects.requireNonNull(username), Objects.requireNonNull(password));

  this.credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, credentials);

  RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create();
  switch (authType) {
  case BASIC:
    authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());
    break;
  case DIGEST:
    authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
    break;
  default:
    throw new IllegalArgumentException("Unsupported authentiation type: " + authType);
  }
  this.authRegistry = authRegistryBuilder.build();
}
 
Example #6
Source File: AbstractUnitTest.java    From elasticsearch-shield-kerberos-realm with Apache License 2.0 6 votes vote down vote up
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);
        }

        hcb.setDefaultCredentialsProvider(credsProvider);
        hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
        final CloseableHttpClient httpClient = hcb.build();
        return httpClient;
    }
 
Example #7
Source File: ConfigServerApiImpl.java    From vespa with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(200); // Increase max total connections to 200, which should be enough

    // Have experienced hang in socket read, which may have been because of
    // system defaults, therefore set explicit timeouts.
    return HttpClientBuilder.create()
            .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG)
            .disableAutomaticRetries()
            .setUserAgent("node-admin")
            .setConnectionManager(cm)
            .build();
}
 
Example #8
Source File: TestInfoServersACL.java    From hbase with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createHttpClient(String clientPrincipal) throws Exception {
  // Logs in with Kerberos via GSS
  GSSManager gssManager = GSSManager.getInstance();
  // jGSS Kerberos login constant
  Oid oid = new Oid("1.2.840.113554.1.2.2");
  GSSName gssClient = gssManager.createName(clientPrincipal, GSSName.NT_USER_NAME);
  GSSCredential credential = gssManager.createCredential(
      gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

  Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
      .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();

  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

  return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
      .setDefaultCredentialsProvider(credentialsProvider).build();
}
 
Example #9
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 #10
Source File: AbstractGremlinServerChannelizerIntegrateTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createSslHttpClient() throws Exception {
    final SSLContextBuilder wsBuilder = new SSLContextBuilder();
    wsBuilder.loadTrustMaterial(null, (chain, authType) -> true);
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wsBuilder.build(),
        new NoopHostnameVerifier());
    //This winds up using a PoolingHttpClientConnectionManager so need to pass the
    //RegistryBuilder
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder
        .<ConnectionSocketFactory> create().register("https", sslsf)
        .build();
    final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    return HttpClients
        .custom()
        .setConnectionManager(cm)
        .build();

}
 
Example #11
Source File: HttpProtocolParent.java    From dtsopensource 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 #12
Source File: CrossOriginResourceSharingResponseTest.java    From s3proxy with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient getHttpClient() throws
        KeyManagementException, NoSuchAlgorithmException,
        KeyStoreException {
    // Relax SSL Certificate check
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
            null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] arg0,
                        String arg1) throws CertificateException {
                    return true;
                }
            }).build();

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

    PoolingHttpClientConnectionManager connectionManager = new
            PoolingHttpClientConnectionManager(registry);

    return HttpClients.custom().setConnectionManager(connectionManager)
            .build();
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
Source File: TelegramHttpClientBuilder.java    From TelegramBots with MIT License 6 votes vote down vote up
private static HttpClientConnectionManager createConnectionManager(DefaultBotOptions options) {
    Registry<ConnectionSocketFactory> registry;
    switch (options.getProxyType()) {
        case NO_PROXY:
            return null;
        case HTTP:
            registry = RegistryBuilder.<ConnectionSocketFactory> create()
                    .register("http", new HttpConnectionSocketFactory())
                    .register("https", new HttpSSLConnectionSocketFactory(SSLContexts.createSystemDefault())).build();
            return new PoolingHttpClientConnectionManager(registry);
        case SOCKS4:
        case SOCKS5:
            registry = RegistryBuilder.<ConnectionSocketFactory> create()
                    .register("http", new SocksConnectionSocketFactory())
                    .register("https", new SocksSSLConnectionSocketFactory(SSLContexts.createSystemDefault()))
                    .build();
            return new PoolingHttpClientConnectionManager(registry);
    }
    return null;
}
 
Example #20
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 #21
Source File: ClientUtil.java    From oxAuth with MIT License 6 votes vote down vote up
/**
 * Creates a special SSLContext using a custom TLS version and a set of ciphers enabled to process SSL connections.
 * @param tlsVersion TLS version, for example TLSv1.2
 * @param ciphers Set of ciphers used to create connections.
 */
public static CloseableHttpClient createHttpClient(String tlsVersion, String[] ciphers) {
    try {
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext,
                new String[] { tlsVersion }, ciphers, NoopHostnameVerifier.INSTANCE);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("https", sslConnectionFactory)
                .register("http", new PlainConnectionSocketFactory())
                .build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);

        return HttpClients.custom()
                .setSSLContext(sslContext)
                .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
                .setConnectionManager(cm)
                .build();
    } catch (Exception e) {
        log.error("Error creating HttpClient with a custom TLS version and custom ciphers", e);
        return null;
    }
}
 
Example #22
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 #23
Source File: HttpClientHelper.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private static Registry<ConnectionSocketFactory> createSocketFactoryConfigration() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final Registry<ConnectionSocketFactory> socketFactoryRegistry;
    final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
    final SSLConnectionSocketFactory cnnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HTTPS, cnnectionSocketFactory)
            .build();

    return socketFactoryRegistry;
}
 
Example #24
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From spring4-understanding with Apache License 2.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 #25
Source File: HttpClientConnectionManagerFactory.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
public static HttpClientConnectionManager withTimeoutMs(int timeoutMs) {
  BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
      RegistryBuilder.<ConnectionSocketFactory>create()
          .register("http", PlainConnectionSocketFactory.getSocketFactory())
          .register("https", new SSLConnectionSocketFactoryWithTimeout(timeoutMs))
          .build());

  httpClientConnectionManager.setSocketConfig(
      SocketConfig.custom().setSoTimeout(timeoutMs).build());

  return httpClientConnectionManager;
}
 
Example #26
Source File: ConsulUtils.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static Registry<ConnectionSocketFactory> setupSchemeRegistry(SSLContext sslContext) {
    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    if (sslContext != null) {
        registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
    }
    return registryBuilder.build();
}
 
Example #27
Source File: RestClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private Registry constructRegistry() {

        try {
            SSLContextBuilder builder = SSLContextBuilder.create();

            builder.useProtocol(this.supportedProtocols[0]);

            if (!StringUtils.isNullOrEmpty(clientConfigurator.getCertificateFileName())) {
                builder.loadKeyMaterial(SslUtils.loadKeystore(clientConfigurator.getCertificateFileName(),
                                                              clientConfigurator.getCertificateFilePassword()),
                                        clientConfigurator.getCertificateFilePassword().toCharArray());
            }

            // Trust all certificates
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {

                    return true;
                }
            });
            SSLContext sslContext = builder.build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                                                                              new NoopHostnameVerifier());

            Registry registry = RegistryBuilder.create().register("https", sslsf).build();

            return registry;
        } catch (Exception e) {
            throw new RuntimeException("Unable to setup SSL context for REST client with Apache connector provider", e);
        }
    }
 
Example #28
Source File: RestClient.java    From light with Apache License 2.0 5 votes vote down vote up
private Registry<ConnectionSocketFactory> registry() throws Exception {

        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(
                sslContext(),
                new String[] { "TLSv1" },
                null,
                hostnameVerifier());

        // Create a registry of custom connection factory
        return RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", sslFactory)
                .build();
    }
 
Example #29
Source File: PilosaClient.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected Registry<ConnectionSocketFactory> getRegistry() {
    HostnameVerifier verifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            this.options.getSslContext(),
            new String[]{"TLSv1.2"}, null, verifier);
    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();
}
 
Example #30
Source File: HttpUtil.java    From ZhihuSpider with MIT License 5 votes vote down vote up
public static HttpClientContext getHttpClientContext() {
    HttpClientContext context = null;
    context = HttpClientContext.create();
    Registry<CookieSpecProvider> registry = RegistryBuilder
            .<CookieSpecProvider>create()
            .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
            .register(CookieSpecs.BROWSER_COMPATIBILITY,
                    new BrowserCompatSpecFactory()).build();
    context.setCookieSpecRegistry(registry);
    return context;
}