类org.apache.http.ssl.SSLContexts源码实例Demo

下面列出了怎么用org.apache.http.ssl.SSLContexts的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: oxAuth   文件: BaseTest.java
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;
}
 
源代码2 项目: yaks   文件: HttpClientSteps.java
/**
 * 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);
    }
}
 
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);
    }
}
 
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;
}
 
源代码5 项目: docker-java-api   文件: SslHttpClient.java
/**
 * 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);
        }
    });
}
 
源代码6 项目: weixin-sdk   文件: WxSslClient.java
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();

}
 
源代码7 项目: common-project   文件: HttpUtil.java
/**
 * 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;
}
 
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);
    }
}
 
源代码9 项目: api-layer   文件: HttpsFactory.java
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;
    }
}
 
源代码10 项目: quarkus   文件: DefaultConsulConfigGateway.java
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);
    }
}
 
源代码11 项目: gerbil   文件: TagMeAnnotator.java
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());
}
 
源代码12 项目: tutorials   文件: HttpsClientSslLiveTest.java
@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();
}
 
源代码13 项目: nextcloud-java-api   文件: ConnectorCommon.java
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;
}
 
源代码14 项目: oxAuth   文件: ClientUtil.java
/**
 * 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;
    }
}
 
源代码15 项目: ScriptSpider   文件: HttpUtils.java
/**
 * 创建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) {

    }
}
 
源代码16 项目: spring-cloud-dashboard   文件: HttpClientUtils.java
/**
 * 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);
	}
}
 
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);
    }
}
 
源代码18 项目: cms   文件: HttpUtils.java
/**
     * 创建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);
        }
    }
 
源代码19 项目: cms   文件: HttpUtils.java
/**
     * 创建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);
        }
    }
 
源代码20 项目: sdk   文件: AviRestUtils.java
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;
}
 
源代码21 项目: dx-java   文件: MPRestClient.java
/**
 * 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();
}
 
源代码22 项目: spring-cloud-contract   文件: WireMockSpring.java
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();
}
 
源代码23 项目: etherjar   文件: HttpRpcTransport.java
/**
 * 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;
}
 
/**
 * 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);
	}
}
 
源代码25 项目: thorntail   文件: HttpsTest.java
@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");
    }
}
 
源代码26 项目: vespa   文件: HealthCheckProxyHandler.java
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);
        }
    }
}
 
源代码27 项目: TelegramBots   文件: TelegramHttpClientBuilder.java
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;
}
 
源代码28 项目: apicurio-studio   文件: DownloadServlet.java
@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);
    }
}
 
源代码29 项目: citrus-simulator   文件: HttpClientConfig.java
@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);
    }
}
 
源代码30 项目: riptide   文件: ManualConfiguration.java
@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());
}
 
 类所在包
 同包方法