org.apache.http.ssl.SSLContexts Java Examples

The following examples show how to use org.apache.http.ssl.SSLContexts. 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: HttpClientFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 7 votes vote down vote up
protected SSLContext generateSSLContext() {
    SSLContextBuilder contextBuilder = SSLContexts.custom();
    try {
        if (getTrustStoreFile() != null) {
            contextBuilder.loadTrustMaterial(getTrustStoreFile(), getTrustStorePassword(), getTrustStrategy());
        }

        if (getKeyStoreFile() != null) {
            contextBuilder.loadKeyMaterial(getKeyStoreFile(), getKeyStorePassword(), getKeyPassword(), getPrivateKeyStrategy());
        }

        return contextBuilder.build();
    } catch (GeneralSecurityException | IOException e) {
        throw new RuntimeException("Unable to configure SSL", e);
    }
}
 
Example #3
Source File: HttpsFactory.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private synchronized SSLContext createSecureSslContext() {
    if (secureSslContext == null) {
        log.debug("Protocol: {}", config.getProtocol());
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        try {
            loadTrustMaterial(sslContextBuilder);
            loadKeyMaterial(sslContextBuilder);
            secureSslContext = sslContextBuilder.build();
            validateSslConfig();
            return secureSslContext;
        } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
                | UnrecoverableKeyException | KeyManagementException e) {
            apimlLog.log("org.zowe.apiml.common.sslContextInitializationError", e.getMessage());
            throw new HttpsConfigError("Error initializing SSL Context: " + e.getMessage(), e,
                    ErrorCode.HTTP_CLIENT_INITIALIZATION_FAILED, config);
        }
    } else {
        return secureSslContext;
    }
}
 
Example #4
Source File: AbstractHACCommunicationManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Creates {@link HttpClient} that trusts any SSL certificate
 *
 * @return prepared HTTP client
 */
protected HttpClient getSSLAcceptingClient() {
	final TrustStrategy trustAllStrategy = (final X509Certificate[] chain, final String authType) -> true;
	try {
		final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustAllStrategy).build();

		sslContext.init(null, getTrustManager(), new SecureRandom());
		final SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
				new NoopHostnameVerifier());

		return HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build();
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException error) {
		ConsoleUtils.printError(error.getMessage());
		throw new IllegalStateException(ErrorMessage.CANNOT_CREATE_SSL_SOCKET, error);
	}
}
 
Example #5
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 #6
Source File: HealthCheckProxyHandler.java    From vespa with Apache License 2.0 6 votes vote down vote up
private SSLContext getSslContext(SslContextFactory.Server sslContextFactory) {
    if (sslContextFactory.getNeedClientAuth()) {
        log.info(String.format("Port %d requires client certificate. HTTPS client will use the target server connector's ssl context.", port));
        // A client certificate is only required if the server connector's ssl context factory is configured with "need-auth".
        // We use the server's ssl context (truststore + keystore) if a client certificate is required.
        // This will only work if the server certificate's CA is in the truststore.
        return sslContextFactory.getSslContext();
    } else {
        log.info(String.format(
                "Port %d does not require a client certificate. HTTPS client will use a custom ssl context accepting all certificates.", port));
        // No client certificate required. The client is configured with a trust manager that accepts all certificates.
        try {
            return SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #7
Source File: HttpsTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
public void hello() throws IOException, GeneralSecurityException {
    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
            .build();
    try (CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLContext(sslContext)
            .build()) {

        String response = Executor.newInstance(httpClient)
                .execute(Request.Get("https://localhost:8443/"))
                .returnContent().asString();
        assertThat(response).contains("Hello on port 8443, secure: true");
    }
}
 
Example #8
Source File: DefaultApacheHttpClientBuilder.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private SSLConnectionSocketFactory buildSSLConnectionSocketFactory() {
  try {
    SSLContext sslcontext = SSLContexts.custom()
      //忽略掉对服务器端证书的校验
      .loadTrustMaterial(new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
          return true;
        }
      }).build();

    return new SSLConnectionSocketFactory(
      sslcontext,
      new String[]{"TLSv1"},
      null,
      SSLConnectionSocketFactory.getDefaultHostnameVerifier());
  } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
    this.log.error(e.getMessage(), e);
  }

  return null;
}
 
Example #9
Source File: DownloadServlet.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
@PostConstruct
protected void postConstruct() {
    try {
        if (uiConfig.isDisableHubApiTrustManager()) {
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } else {
            httpClient = HttpClients.createSystem();
        }
    } catch (Exception e) {
        logger.error("Error creating HTTP client.", e);
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: ManualConfiguration.java    From riptide with MIT License 6 votes vote down vote up
@Bean
public ApacheClientHttpRequestFactory exampleAsyncClientHttpRequestFactory(
        final Flow flow) throws Exception {
    return new ApacheClientHttpRequestFactory(
            HttpClientBuilder.create()
                    .setDefaultRequestConfig(RequestConfig.custom()
                            .setConnectTimeout(5000)
                            .setSocketTimeout(5000)
                            .build())
                    .setConnectionTimeToLive(30, SECONDS)
                    .setMaxConnPerRoute(2)
                    .setMaxConnTotal(20)
                    .addInterceptorFirst(new FlowHttpRequestInterceptor(flow))
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(
                            SSLContexts.custom()
                                    .loadTrustMaterial(
                                            getClass().getClassLoader().getResource("example.keystore"),
                                            "password".toCharArray())
                                    .build(),
                            getDefaultHostnameVerifier()))
                    .build());
}
 
Example #11
Source File: HttpClientSteps.java    From yaks with Apache License 2.0 6 votes vote down vote up
/**
 * Get secure http client implementation with trust all strategy and noop host name verifier.
 * @return
 */
private org.apache.http.client.HttpClient sslClient() {
    try {
        SSLContext sslcontext = SSLContexts
                .custom()
                .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslcontext, NoopHostnameVerifier.INSTANCE);

        return HttpClients
                .custom()
                .setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new CitrusRuntimeException("Failed to create http client for ssl connection", e);
    }
}
 
Example #12
Source File: HttpClientConfig.java    From citrus-simulator with Apache License 2.0 6 votes vote down vote up
@Bean
public CloseableHttpClient httpClient() {
    try {
        //new ClassPathResource("").getURL()
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(keyStore, keyPassword.toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslcontext, NoopHostnameVerifier.INSTANCE);

        return HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new BeanCreationException("Failed to create http client for ssl connection", e);
    }
}
 
Example #13
Source File: ClouderaManagerApiClientProvider.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private ApiClient decorateClient(HttpClientConfig clientConfig, String userName, String password, ApiClient cmClient) throws Exception {
    cmClient.setUsername(userName);
    cmClient.setPassword(password);
    cmClient.setVerifyingSsl(true);

    try {
        if (isCmSslConfigValidClientConfigValid(clientConfig) && !clientConfig.isClusterProxyEnabled()) {
            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(KeyStoreUtil.createTrustStore(clientConfig.getServerCert()), null)
                    .loadKeyMaterial(KeyStoreUtil.createKeyStore(clientConfig.getClientCert(), clientConfig.getClientKey()), "consul".toCharArray())
                    .build();
            cmClient.getHttpClient().setSslSocketFactory(sslContext.getSocketFactory());
            cmClient.getHttpClient().setHostnameVerifier(CertificateTrustManager.hostnameVerifier());
        }
        cmClient.getHttpClient().setConnectTimeout(1L, TimeUnit.MINUTES);
        cmClient.getHttpClient().setReadTimeout(1L, TimeUnit.MINUTES);
        cmClient.getHttpClient().setWriteTimeout(1L, TimeUnit.MINUTES);
        return cmClient;
    } catch (Exception e) {
        LOGGER.info("Cannot create SSL context for Cloudera Manager", e);
        throw new ClouderaManagerClientInitException("Couldn't create client", e);
    }
}
 
Example #14
Source File: SslHttpClient.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Ctor.
 * @param keys Path to the keystore.
 * @param trust Path to the truststore.
 * @param storePwd Password for the keystore.
 * @param keyPwd Passphrase for the key.
 */
SslHttpClient(
    final Path keys, final Path trust,
    final char[] storePwd, final char[] keyPwd) {
    this(() -> {
        try {
            return HttpClients.custom()
                .setMaxConnPerRoute(10)
                .setMaxConnTotal(10)
                .setSSLContext(
                    SSLContexts.custom()
                        .loadTrustMaterial(trust.toFile())
                        .loadKeyMaterial(keys.toFile(), storePwd, keyPwd)
                        .build()
                )
                .addInterceptorFirst(new UserAgentRequestHeader())
                .build();
        } catch (final IOException | GeneralSecurityException ex) {
            throw new IllegalStateException(ex);
        }
    });
}
 
Example #15
Source File: WxSslClient.java    From weixin-sdk with Apache License 2.0 6 votes vote down vote up
public WxSslClient(String certPath, String certPassword) {
    KeyStore keyStore = null;
    SSLContext sslcontext = null;
    try {
        keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream inputStream = new FileInputStream(new File(certPath));
        keyStore.load(inputStream, certPassword.toCharArray());
        sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, certPassword.toCharArray()).build();
    } catch (Exception e) {
        logger.error("initializing WxHttpsClient failed.", e);
        throw new WxRuntimeException(999, e.getMessage());
    }

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();;

    requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(30000).setConnectionRequestTimeout(30000).build();

}
 
Example #16
Source File: HttpUtil.java    From common-project with Apache License 2.0 6 votes vote down vote up
/**
 * https请求
 * 
 * @param certificatePath
 * @param secretKey
 * @return
 */
@SuppressWarnings("deprecation")
public static CloseableHttpClient createSSL(String certificatePath, String secretKey) {
    KeyStore keyStore = null;
    CloseableHttpClient httpclient = null;
    try {
        keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(certificatePath));
        try {
            keyStore.load(instream, secretKey.toCharArray());
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, secretKey.toCharArray()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return httpclient;
}
 
Example #17
Source File: HttpGenericOperationUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    try {
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(username, password));
        PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
        HttpClientBuilder.create().setConnectionManager(connectionPool).build();
        return HttpClientBuilder.create()
                .setConnectionManager(connectionPool)
                .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: DefaultConsulConfigGateway.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private SSLConnectionSocketFactory createFactoryFromAgentConfig(ConsulConfig.AgentConfig agentConfig) {
    try {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        if (agentConfig.trustStore.isPresent()) {
            sslContextBuilder = sslContextBuilder
                    .loadTrustMaterial(readStore(agentConfig.trustStore.get(), agentConfig.trustStorePassword), null);
        } else if (agentConfig.trustCerts) {
            sslContextBuilder = sslContextBuilder.loadTrustMaterial(TrustAllStrategy.INSTANCE);
        }
        if (agentConfig.keyStore.isPresent()) {
            String keyPassword = agentConfig.keyPassword.orElse(agentConfig.keyStorePassword.orElse(""));
            sslContextBuilder = sslContextBuilder.loadKeyMaterial(
                    readStore(agentConfig.keyStore.get(), agentConfig.keyStorePassword), keyPassword.toCharArray());
        }
        return new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | IOException | CertificateException
            | UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: TagMeAnnotator.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void init() throws GerbilException {
    HttpClientBuilder builder = HttpManagement.getInstance().generateHttpClientBuilder();
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream instream = this.getClass().getClassLoader().getResourceAsStream(KEY_STORE_RESOURCE_NAME);
        try {
            keyStore.load(instream, KEY_STORE_PASSWORD);
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy())
                .build();
        builder.setSSLContext(sslcontext);

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslsf);
        CloseableHttpClient localClient = builder.build();
        this.setClient(localClient);
    } catch (Exception e) {
        throw new GerbilException("Couldn't initialize SSL context.", e, ErrorTypes.ANNOTATOR_LOADING_ERROR);
    }
    this.setClient(builder.build());
}
 
Example #20
Source File: HttpRpcTransport.java    From etherjar with Apache License 2.0 6 votes vote down vote up
/**
 * Provide a trusted x509 certificate expected from RPC server
 *
 * @param certificate input stream to certificate in DER format (binary or base64)
 * @throws GeneralSecurityException if there is a problem with the certificate
 * @throws IOException if unable to read certificate
 * @return builder
 */
public Builder trustedCertificate(InputStream certificate) throws GeneralSecurityException, IOException {
    this.httpClient = null;

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(certificate);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, "".toCharArray());
    ks.setCertificateEntry("server", cert);
    this.sslContext = SSLContexts.custom()
        .loadTrustMaterial(ks, (TrustStrategy) (chain, authType) -> Arrays.asList(chain).contains(cert))
        .build();

    return this;
}
 
Example #21
Source File: WireMockSpring.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
public static WireMockConfiguration options() {
	if (!initialized) {
		if (ClassUtils.isPresent("org.apache.http.conn.ssl.NoopHostnameVerifier",
				null)) {
			HttpsURLConnection
					.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
			try {
				HttpsURLConnection.setDefaultSSLSocketFactory(SSLContexts.custom()
						.loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE)
						.build().getSocketFactory());
			}
			catch (Exception e) {
				throw new AssertionError("Cannot install custom socket factory: ["
						+ e.getMessage() + "]");
			}
		}
		initialized = true;
	}
	return new WireMockConfiguration();
}
 
Example #22
Source File: HttpsClientSslLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
    final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
    
    final SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build();

    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
    PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

    final CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .setConnectionManager(clientConnectionManager)
            .build();

    final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
    final HttpResponse response = httpClient.execute(getMethod);
    assertThat(response.getStatusLine()
        .getStatusCode(), equalTo(200));

    httpClient.close();
}
 
Example #23
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
public static CloseableHttpAsyncClient getInstance(ServerConfig serverConfig)
	throws IOException{
	if (HTTPC_CLIENT == null) {
		if (serverConfig.isTrustAllCertificates()) {
			try {
				SSLContext sslContext = SSLContexts.custom()
					.loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();
				HTTPC_CLIENT = HttpAsyncClients.custom()
					.setSSLHostnameVerifier((NoopHostnameVerifier.INSTANCE))
					.setSSLContext(sslContext)
					.build();
			} catch (KeyManagementException | NoSuchAlgorithmException
					| KeyStoreException e) {
				throw new IOException(e);
			} 
			
		} else {
			HTTPC_CLIENT = HttpAsyncClients.createDefault();
		}
		
		HTTPC_CLIENT.start();
	}
	return HTTPC_CLIENT;
}
 
Example #24
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 #25
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 #26
Source File: HttpClientUtils.java    From spring-cloud-dashboard with Apache License 2.0 6 votes vote down vote up
/**
 * Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution as it undermines security,
 * but may be useful in certain testing or development scenarios.
 *
 * @return The SSLContext
 */
public static SSLContext buildCertificateIgnoringSslContext() {
	try {
		return SSLContexts
			.custom()
			.loadTrustMaterial(new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
					return true;
				}
			})
			.build();
	}
	catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.", e);
	}
}
 
Example #27
Source File: AviRestUtils.java    From sdk with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpClient buildHttpClient(AviCredentials creds) {
	CloseableHttpClient httpClient = null;
	if (!creds.getVerify()) {
		SSLContext sslcontext = null;
		try {
			sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
		} catch (Exception e) {
			e.printStackTrace();
		}

		SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext,
				(s, sslSession) -> true);

		httpClient = HttpClients.custom().setRetryHandler(retryHandler(creds))
				.setSSLSocketFactory(sslConnectionSocketFactory)
				.setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(
						creds.getNumApiRetries(), creds.getRetryWaitTime())).disableCookieManagement()
				.build();
	} else {
		httpClient = HttpClients.custom().setRetryHandler(retryHandler(creds))
				.setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(
						creds.getNumApiRetries(), creds.getRetryWaitTime())).disableCookieManagement()
				.build();
	}
	return httpClient;
}
 
Example #28
Source File: BaseTest.java    From oxAuth with MIT License 6 votes vote down vote up
public static CloseableHttpClient createHttpClientTrustAll()
		throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
	SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
		@Override
		public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			return true;
		}
	}).build();
	SSLConnectionSocketFactory sslContextFactory = new SSLConnectionSocketFactory(sslContext);
	CloseableHttpClient httpclient = HttpClients.custom()
			.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
			.setSSLSocketFactory(sslContextFactory)
			.setRedirectStrategy(new LaxRedirectStrategy()).build();

	return httpclient;
}
 
Example #29
Source File: HttpUtils.java    From cms with Apache License 2.0 6 votes vote down vote up
/**
     * 创建SSL安全连接
     *
     * @return
     */
    private static SSLConnectionSocketFactory createSSLSocketFactory() {
        try {

            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
//			new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, NoopHostnameVerifier.INSTANCE);

            return socketFactory;
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.",
                    e);
        }
    }
 
Example #30
Source File: HttpUtils.java    From cms with Apache License 2.0 6 votes vote down vote up
/**
     * 创建SSL安全连接
     *
     * @return
     */
    private static SSLConnectionSocketFactory createSSLSocketFactory() {
        try {

            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
//			new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, NoopHostnameVerifier.INSTANCE);

            return socketFactory;
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.",
                    e);
        }
    }