org.apache.http.conn.ssl.SSLConnectionSocketFactory Java Examples

The following examples show how to use org.apache.http.conn.ssl.SSLConnectionSocketFactory. 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: ConnectionManager.java    From curly with Apache License 2.0 6 votes vote down vote up
private void createNewConnectionManager() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(new TrustSelfSignedStrategy());

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                builder.build(), NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory())
                .register("https", sslsf)
                .build();
        connectionManager = new PoolingHttpClientConnectionManager(r);
        connectionManager.setValidateAfterInactivity(500);
        sharedContext = ThreadLocal.withInitial(HttpClientContext::new);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
    }

}
 
Example #3
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 #4
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 #5
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 #6
Source File: HttpUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void setSkipCertificateValidation() {
    if (!tlsWarningEmitted.getAndSet(true)) {
        // Since this is a static util, it may happen that TLS is setup many times in one command
        // invocation (e.g. when a command requires logging in). However, we would like to
        // prevent this warning from appearing multiple times. That's why we need to guard it with a boolean.
        System.err.println("The server is configured to use TLS but there is no truststore specified.");
        System.err.println("The tool will skip certificate validation. This is highly discouraged for production use cases");
    }

    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build());
    } catch (Exception e) {
        throw new RuntimeException("Failed setting up TLS", e);
    }
}
 
Example #7
Source File: RequestProcessor.java    From cellery-distribution with Apache License 2.0 6 votes vote down vote up
public RequestProcessor() throws APIException {
    try {
        if (log.isDebugEnabled()) {
            log.debug("Ignoring SSL verification...");
        }
        SSLContext sslContext = SSLContext.getInstance("SSL");

        X509TrustManager x509TrustManager = new TrustAllTrustManager();
        sslContext.init(null, new TrustManager[] {x509TrustManager}, new SecureRandom());

        SSLConnectionSocketFactory sslsocketFactory =
                new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null,
                        (s, sslSession) -> true);

        httpClient = HttpClients.custom().setSSLSocketFactory(sslsocketFactory).build();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        String errorMessage = "Error occurred while ignoring ssl certificates to allow http connections";
        log.error(errorMessage, e);
        throw new APIException(errorMessage, e);
    }
}
 
Example #8
Source File: HttpUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpClient ceateSSLClient(File keyFile, String protocol, String password){ 
	CloseableHttpClient httpclient = null; 
	try{ 
		KeyStore keyStore  = KeyStore.getInstance("PKCS12"); 
        FileInputStream instream = new FileInputStream(keyFile); 
        try { 
            keyStore.load(instream, password.toCharArray()); 
        } finally { 
            instream.close(); 
        } 
		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build(); 
        String[] protocols = new String[] {protocol};
		//ALLOW_ALL_HOSTNAME_VERIFIER  关闭host验证,允许和所有的host建立SSL通信                  
		//BROWSER_COMPATIBLE_HOSTNAME_VERIFIER  和浏览器兼容的验证策略,即通配符能够匹配所有子域名
		//STRICT_HOSTNAME_VERIFIER  严格匹配模式,hostname必须匹配第一个CN或者任何一个subject-alts
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,protocols,null,
				SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); 
	}catch(Exception e){ 
		e.printStackTrace(); 
	} 
	return httpclient; 
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
Source File: HttpUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void setSkipCertificateValidation() {
    if (!tlsWarningEmitted.getAndSet(true)) {
        // Since this is a static util, it may happen that TLS is setup many times in one command
        // invocation (e.g. when a command requires logging in). However, we would like to
        // prevent this warning from appearing multiple times. That's why we need to guard it with a boolean.
        System.err.println("The server is configured to use TLS but there is no truststore specified.");
        System.err.println("The tool will skip certificate validation. This is highly discouraged for production use cases");
    }

    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build());
    } catch (Exception e) {
        throw new RuntimeException("Failed setting up TLS", e);
    }
}
 
Example #14
Source File: HttpsClientSslLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenHttpClientAfter4_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);

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

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

    httpClient.close();
}
 
Example #15
Source File: HttpManagementInterface.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) {
    SSLContext sslContext = org.apache.http.ssl.SSLContexts.createDefault();
                SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory)
                    .build();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                    new UsernamePasswordCredentials(username, password));

    return HttpClientBuilder.create()
                    .setConnectionManager(new PoolingHttpClientConnectionManager(registry))
                    .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                    .setDefaultCredentialsProvider(credentialsProvider)
                    .build();
}
 
Example #16
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 #17
Source File: HttpClientFactory.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
public HttpClientFactory build() {

            if (this.sslSocketFactory == null) {
                this.sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            }
            if (this.plainSocketFactory == null) {
                this.plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
            }
            if (this.httpIOSessionStrategy == null) {
                this.httpIOSessionStrategy = NoopIOSessionStrategy.INSTANCE;
            }
            if (this.httpsIOSessionStrategy == null) {
                this.httpsIOSessionStrategy = SSLIOSessionStrategy.getSystemDefaultStrategy();
            }

            return new HttpClientFactory(this);
        }
 
Example #18
Source File: WebhookService.java    From webanno with Apache License 2.0 6 votes vote down vote up
public WebhookService()
    throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException
{
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain,
            String authType) -> true;

    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy).build();

    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

    nonValidatingRequestFactory = new HttpComponentsClientHttpRequestFactory();
    nonValidatingRequestFactory.setHttpClient(httpClient);
}
 
Example #19
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 #20
Source File: S3Util.java    From teamcity-s3-artifact-storage-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
private static ConnectionSocketFactory socketFactory(@NotNull final Map<String, String> params) {
  final String certDirectory = params.get(SSL_CERT_DIRECTORY_PARAM);
  if (certDirectory == null) {
    return null;
  }
  final KeyStore trustStore = trustStore(certDirectory);
  if (trustStore == null) {
    return null;
  }
  final SSLContext sslContext = SSLContextUtil.createUserSSLContext(trustStore);
  if (sslContext == null) {
    return null;
  }
  return new SSLConnectionSocketFactory(sslContext);
}
 
Example #21
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 #22
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the {@code HostnameVerifier} given the provided {@code verification}.
 *
 * @param verification The intended hostname verification action.
 * @return A verifier for the request verification.
 * @throws IllegalArgumentException if the provided verification cannot be handled.
 */
HostnameVerifier getHostnameVerifier(HostnameVerification verification) {
  // Normally, the configuration logic would give us a default of STRICT if it was not
  // provided by the user. It's easy for us to do a double-check.
  if (verification == null) {
    verification = HostnameVerification.STRICT;
  }
  switch (verification) {
  case STRICT:
    return SSLConnectionSocketFactory.getDefaultHostnameVerifier();
  case NONE:
    return NoopHostnameVerifier.INSTANCE;
  default:
    throw new IllegalArgumentException("Unhandled HostnameVerification: "
        + hostnameVerification);
  }
}
 
Example #23
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 #24
Source File: SecurityUtils.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    final char[] pwd = password.toCharArray();
    SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
            .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
    ;
    if (keystoreFile != null) {
        sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
    }

    sslcontextBuilder.setProtocol("TLSv1.2");

    return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(final String s, final SSLSession sslSession) {
            return true;
        }
    });
}
 
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: HttpClientFactoryTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildHttpClientAuthenticationWithoutPass()
{
    prepareClientBuilderUtilsMock();

    testBuildHttpClientUsingConfig();

    verify(mockedHttpClientBuilder, never()).setDefaultCredentialsProvider(any(CredentialsProvider.class));
    verify(mockedHttpClientBuilder, never()).setSSLSocketFactory(any(SSLConnectionSocketFactory.class));
    PowerMockito.verifyStatic(ClientBuilderUtils.class, never());
    ClientBuilderUtils.createCredentialsProvider(any(AuthScope.class), anyString(), anyString());
}
 
Example #27
Source File: SFSSLConnectionSocketFactory.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
public SFSSLConnectionSocketFactory(TrustManager[] trustManagers,
                                    boolean socksProxyDisabled)
throws NoSuchAlgorithmException, KeyManagementException
{
  super(
      initSSLContext(trustManagers),
      new String[]{SSL_VERSION},
      decideCipherSuites(),
      SSLConnectionSocketFactory.getDefaultHostnameVerifier()
  );
  this.socksProxyDisabled = socksProxyDisabled;
}
 
Example #28
Source File: HttpClientFactoryTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildHttpClientWithFullAuthentication()
{
    config.setCredentials(CREDS);
    config.setAuthScope(AUTH_SCOPE);

    prepareClientBuilderUtilsMock();

    testBuildHttpClientUsingConfig();

    verify(mockedHttpClientBuilder).setDefaultCredentialsProvider(credentialsProvider);
    verify(mockedHttpClientBuilder, never()).setSSLSocketFactory(any(SSLConnectionSocketFactory.class));
    PowerMockito.verifyStatic(ClientBuilderUtils.class);
    ClientBuilderUtils.createCredentialsProvider(AUTH_SCOPE, CREDS);
}
 
Example #29
Source File: HttpsRequest.java    From pay with Apache License 2.0 5 votes vote down vote up
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(config.getCertLocalPath()));//加载本地的证书进行https加密传输
        try {
            keyStore.load(instream,config.getCertPassword().toCharArray());//设置证书密码
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, config.getCertPassword().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();

        //根据默认超时限制初始化requestConfig
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();

        hasInit = true;
    }
 
Example #30
Source File: ClientApplication.java    From mtls-springboot with The Unlicense 5 votes vote down vote up
private HttpClient httpClient() throws Exception {
    // Load our keystore and truststore containing certificates that we trust.
    SSLContext sslcontext =
            SSLContexts.custom().loadTrustMaterial(trustStore.getFile(), trustStorePassword.toCharArray())
                    .loadKeyMaterial(keyStore.getFile(), keyStorePassword.toCharArray(),
                            keyPassword.toCharArray()).build();
    SSLConnectionSocketFactory sslConnectionSocketFactory =
            new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());
    return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}