Java org.apache.http.conn.ssl.SSLConnectionSocketFactory 代码实例

・29 分钟阅读

以下是展示如何使用org.apache.http.conn.ssl.SSLConnectionSocketFactory的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public static HttpClient getHttpClientWithSSL(File keyStoreFile, String keyStorePassword, File trustStoreFile,
                                              String trustStorePassword) {
    try {
        final KeyStore truststore = loadKeyStore(trustStoreFile, trustStorePassword.toCharArray());
        final KeyStore keystore = keyStoreFile != null ? loadKeyStore(keyStoreFile, keyStorePassword.toCharArray()) : null;
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .useTLS()
                .loadTrustMaterial(truststore);
        if (keyStoreFile!=null){
            sslContextBuilder.loadKeyMaterial(keystore, keyStorePassword.toCharArray());
        }
        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,new AllowAllHostnameVerifier());
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", socketFactory)
                .build();
        return HttpClientBuilder.create()
                .setSSLSocketFactory(socketFactory)
                .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                .setConnectionManager(new PoolingHttpClientConnectionManager(registry))
                .setSchemePortResolver(new DefaultSchemePortResolver())
                .build();
    } catch (Exception e) {
        LOGGER.error("Creating HttpClient with customized SSL failed. We are returning the default one instead.", e);
        return HttpClients.createDefault();
    }
}
 

实例 2


static String secureContentFor(String url, String clientTrustStore, String trustStorePassword) throws Exception {
    KeyStore trustStore = readKeyStore(clientTrustStore, trustStorePassword);
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
            .loadKeyMaterial(trustStore, trustStorePassword.toCharArray())
            .useTLS()
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslcontext,
            new String[] { "TLSv1" }, // supported protocols
            null,  // supported cipher suites
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .build();
    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    String content = EntityUtils.toString(response.getEntity());
    return content;
}
 

实例 3


/**
 * This code sets up the httpclient to accept any SSL certificate. The 
 * SSL certificate generated by the instructions 上面 is not correctly
 * signed, so we need ignore the problem. 
 * This code should not, under any circumstances, be allowed anywhere 
 * the production code. 
 * @return
 */
private CloseableHttpClient createClient () {
    try {
        HttpClientBuilder builder = HttpClientBuilder.create();
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[]{getTrustManager()}, null);
        SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(ctx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        builder.setSSLSocketFactory(scsf);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", scsf)
                .build();
        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
        builder.setConnectionManager(ccm);
        return builder.build();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 

实例 4


protected final HeaderAwareJestHttpClient getJestClient(final String serverUri, final String username, final String password)
        throws Exception {// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();
    // Construct a new Jest client according to configuration via factory
    final HeaderAwareJestClientFactory factory1 = new HeaderAwareJestClientFactory();
    factory1.setHttpClientConfig(clientConfig1);
    final HeaderAwareJestHttpClient c = factory1.getObject();
    final HttpClientBuilder hcb = HttpClients.custom();
    if (username != null) {
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(username, password));
    }
    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);//  new NegotiateSchemeProvider();
        final Credentials jaasCreds = new JaasCredentials();
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest",
                "Guest"));
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
                .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();
        hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }
    hcb.setDefaultCredentialsProvider(credsProvider);
    if (serverUri.startsWith("https")) {
        log.debug("Configure Jest with SSL");
        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("SearchguardTS.jks")),
                "changeit".toCharArray());
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("SearchguardKS.jks")), "changeit".toCharArray());
        final SSLContext sslContext = SSLContexts.custom().useTLS().loadKeyMaterial(keyStore, "changeit".toCharArray())
                .loadTrustMaterial(myTrustStore).build();
        String[] protocols = null;
        if (enableSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = SecurityUtil.ENABLED_SSL_PROTOCOLS;
        }
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols,
                SecurityUtil.ENABLED_SSL_CIPHERS, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        hcb.setSSLSocketFactory(sslsf);
    }
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());
    final CloseableHttpClient httpClient = hcb.build();
    c.setHttpClient(httpClient);
    return c;
}
 

实例 5


private void startHttpClient() {
    if (httpClient != null) {
        // http client is already started
        return;
    }
    // limit max  number of async requests in sequential mode, 0 means "use
    // default limit"
    int maxConnTotal = sendMode == SendMode.Sequential ? 1 : 0;
    if (! disableCertificateValidation) {
        // create an http client that validates certificates
        httpClient = HttpAsyncClients.custom()
                .setMaxConnTotal(maxConnTotal)
                .build();
    } else {
        // create strategy that accepts all certificates
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] certificate,
                                     String type) {
                return true;
            }
        };
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(
                    null, acceptingTrustStrategy).build();
            httpClient = HttpAsyncClients.custom()
                    .setMaxConnTotal(maxConnTotal)
                    .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                    .setSSLContext(sslContext)
                    .build();
        } catch (Exception e) { }
    }
    httpClient.start();
}
 

实例 6


/**
 * This methods checks HTTP, HTTPS and HTTPS with Mutual Authentication.
 */
@Test
public void testCreationOfThreeServersFromConfiguration() throws InterruptedException, IOException,
        KeyStoreException, CertificateException, NoSuchAlgorithmException,
        KeyManagementException, UnrecoverableKeyException {
    FakeConfiguration s1 = new FakeConfiguration(ImmutableMap.<String, Object>builder()
            .put("port", 0)
            .put("ssl", false)
            .put("authentication", false)
            .build());
    FakeConfiguration s2 = new FakeConfiguration(ImmutableMap.<String, Object>builder()
            .put("port", 0)
            .put("ssl", true)
            .put("authentication", false)
            .build());
    FakeConfiguration s3 = new FakeConfiguration(ImmutableMap.<String, Object>builder()
            .put("port", 0)
            .put("ssl", true)
            .put("authentication", true)
            .build());
    // Server HTTPS
    File root = new File("");
    final File serverKeyStore = new File(root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks");
    assertThat(serverKeyStore).isFile();
    when(application.get("https.keyStore")).thenReturn(
            serverKeyStore.getAbsolutePath());
    when(application.get("https.trustStore")).thenReturn(
            new File(root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks").getAbsolutePath());
    when(application.getWithDefault("https.keyStoreType", "JKS")).thenReturn("JKS");
    when(application.getWithDefault("https.trustStoreType", "JKS")).thenReturn("JKS");
    when(application.getWithDefault("https.keyStorePassword", "")).thenReturn("wisdom");
    when(application.getWithDefault("https.trustStorePassword", "")).thenReturn("wisdom");
    when(application.getWithDefault("https.keyStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm()))
            .thenReturn(KeyManagerFactory.getDefaultAlgorithm());
    when(application.getWithDefault("https.trustStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm()))
            .thenReturn(KeyManagerFactory.getDefaultAlgorithm());
    when(application.getConfiguration("vertx.servers")).thenReturn(
            new FakeConfiguration(
                    ImmutableMap.<String, Object>of(
                            "s1", s1,
                            "s2", s2,
                            "s3", s3
                    )
            ));
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok("Alright");
        }
    };
    Route route = new RouteBuilder().route(HttpMethod.GET)
            .on("/")
            .to(controller, "index");
    when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);
    wisdom.start();
    waitForStart(wisdom);
    waitForHttpsStart(wisdom);
    assertThat(wisdom.servers).hasSize(3);
    // Check rendering
    for (Server server : wisdom.servers) {
        String r;
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream("src/test/resources/keystore/client/client1.jks");
        trustStore.load(instream, "wisdom".toCharArray());
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                .loadKeyMaterial(trustStore, "wisdom".toCharArray())
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1", "SSLv3"},
                null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        if (server.ssl()) {
            HttpGet httpget = new HttpGet("https://localhost:" + server.port());
            final CloseableHttpResponse response = httpclient.execute(httpget);
            r = EntityUtils.toString(response.getEntity());
        } else {
            r = org.apache.http.client.fluent.Request
                    .Get("http://localhost:" + server.port()).execute().returnContent().asString();
        }
        assertThat(r).isEqualToIgnoringCase("Alright");
    }
}
 

实例 7


public RestClientBuilder setupSSL(ApiServerConfig cfg) {
    SSLContext sslContext;
    ConnectorFactory factory = cfg.getClientConfig();
    if (factory == null || !(factory instanceof HttpsConnectorFactory))
        return this;
    HttpsConnectorFactory hcf = (HttpsConnectorFactory) factory;
    if (hcf.getKeyStorePath() != null) {
        keyStore = hcf.getKeyStorePath();
        keyStorePassword = hcf.getKeyStorePassword();
        trustStore = hcf.getTrustStorePath();
        trustStorePassword = hcf.getTrustStorePassword();
        sslContext = getSSLContext();
    } else {
        SslConfigurator sslConfig = SslConfigurator.newInstance();
        sslContext = sslConfig.createSSLContext();
    }
    SSLConnectionSocketFactory sslConnectionSocketFactory = hcf.isValidateCerts() ?
            new SSLConnectionSocketFactory(sslContext) :
            new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> registry =
            RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory).build();
    using(registry);
    return this;
}
 

实例 8


/**
 * @param certAuthorityFile The cert authority file, used to determine the authenticity of the
 *         server's SSL certificate.
 * @param authCert The authenticating certificate, used by Lightblue to authenticate.
 * @param authCertPassword The password for the authenticating certificate.
 * @param authCertAlias The alias for the authenticating certificate.
 * @return A default SSL socket factory that assumes a Lightblue instance configured to use
 * SSL certificate based authentication. It does not accept self signed certs, and instead must
 * be provided a certificate authority file to communicate with the Lightblue server.
 */
public static SSLConnectionSocketFactory defaultCertAuthSocketFactory(
        InputStream certAuthorityFile, InputStream authCert, char[] authCertPassword,
        String authCertAlias)
                throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException,
                UnrecoverableKeyException, KeyManagementException {
    X509Certificate cert = getCertificate(certAuthorityFile);
    KeyStore pkcs12KeyStore = getPkcs12KeyStore(authCert, authCertPassword);
    KeyStore sunKeyStore = getJksKeyStore(cert, pkcs12KeyStore, authCertAlias, authCertPassword);
    SSLContext sslContext = getDefaultSSLContext(sunKeyStore, pkcs12KeyStore, authCertPassword);
    return new SSLConnectionSocketFactory(sslContext, SUPPORTED_PROTOCOLS, SUPPORTED_CIPHER_SUITES,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
 

实例 9


/**
 configure HttpClient to ignore self-signed certs
 as described here: http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/
*/
private CloseableHttpClient createTrustingHttpClient() throws IOException {
  try {
    HttpClientBuilder builder = HttpClientBuilder.create();
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustAllStrategy()).build();
    builder.setSslcontext(sslContext);
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    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 e) {
    throw new IOException(e);
  }
}
 

实例 10


private SSLConnectionSocketFactory getLenientSslSocketFactory()
{
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslContext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return sslsf;
}
 

实例 11


@Nullable
private HttpResponse handleCertificateExceptionAndRetry(IOException e,
                                                        HttpRequestBase method,
                                                        HttpClientBuilder client,
                                                        @Nullable HttpContext context)
        throws IOException {
    if (!isCertificateException(e)) {
        throw e;
    }
    if (isTrusted(method.getURI().getAuthority())) {
        // creating a special configuration that allows connections to non-trusted HTTPS hosts
        try {
            SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
            sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionSocketFactory)
                    .build();
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            client.setConnectionManager(connectionManager);
        } catch (Exception sslException) {
            throw Throwables.propagate(sslException);
        }
        return client.build().execute(method, context);
    }
    throw e;
}
 

实例 12


private static CloseableHttpClient getAllTrustClient(HttpHost proxy) {
        return HttpClients.custom()
                        .setProxy(proxy)
                        .setSslcontext(getSSLContext())
                        .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                        .build();
}
 

实例 13


protected SimpleResponse get(String url) throws IllegalStateException, IOException, JettyBootstrapException, NoSuchAlgorithmException, KeyStoreException,
                KeyManagementException {
        SimpleResponse simpleResponse = new SimpleResponse();
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).build();
        if (ssl) {
                SSLContextBuilder sSLContextBuilder = new SSLContextBuilder();
                sSLContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
                SSLConnectionSocketFactory sSLConnectionSocketFactory = new SSLConnectionSocketFactory(sSLContextBuilder.build(),
                                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                httpClient = HttpClients.custom().setSSLSocketFactory(sSLConnectionSocketFactory).build();
                httpGet = new HttpGet("https://" + HOST + ":" + getPort() + url);
        } else {
                httpClient = HttpClients.createDefault();
                httpGet = new HttpGet("http://" + HOST + ":" + getPort() + url);
        }
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
                response = httpClient.execute(httpGet);
                simpleResponse.setStatusCode(response.getStatusLine().getStatusCode());
                simpleResponse.setContent(IOUtils.toString(response.getEntity().getContent()));
        } finally {
                if (response != null) {
                        response.close();
                }
                httpClient.close();
        }
        return simpleResponse;
}
 

实例 14


public IEMAPI(Client client, URI uri, String username, String password) throws JAXBException{
        this.client = client;
        this.baseURI = uri;
        authFilter = new HttpBasicAuthFilter(username,password);
        root = client.target(UriBuilder.fromUri(baseURI)).register(authFilter);
       apiRoot = root.path("/api/");
       this.username = username;
       JAXBContext context = JAXBContext.newInstance(QueryResult.class);
       JAXBContext besContext = JAXBContext.newInstance(BESAPI.class,BES.class);
        queryUnmarshaller = context.createUnmarshaller();
        besUnmarshaller = besContext.createUnmarshaller();
        SSLContext sslContext = client.getSslContext();
        SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register(uri.getScheme(),factory)
                        .build();
        HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, 
            new UsernamePasswordCredentials(username, password));
        apacheHttpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(credentialsProvider)
                .setConnectionManager(cm)
                .build();
}
 

实例 15


private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClientBuilder _builder = HttpClientBuilder.create()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectTimeout(__connectionTimeout)
                    .setSocketTimeout(__connectionTimeout)
                    .setConnectionRequestTimeout(__connectionTimeout).build());
    if (__socketFactory == null) {
        __socketFactory = new SSLConnectionSocketFactory(
                SSLContexts.custom().useSSL().build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    return _builder.setSSLSocketFactory(__socketFactory).build();
}
 
讨论
淘淘あ西西 profile image