在 Apache HttpAsyncClient 中配置 SSL

Configuring SSL in Apache HttpAsyncClient

我需要设置一个支持 SSL 的 Apache HTTPAsyncClient。我使用这段代码,但它似乎不起作用(得到 "javax.net.ssl.SSLException: Received fatal alert: handshake_failure")

    System.setProperty("javax.net.debug", "ssl,handshake");
    System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");

    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(loadStream("C:/TrustStore/cacerts"), "trustpass".toCharArray());
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(loadStream("C:/KeyStore/SSL/keystore.SomeKey"), "keypass".toCharArray());

    SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(ts).loadKeyMaterial(ks, "somekey".toCharArray()).setSecureRandom(new SecureRandom());        
    SSLContext ssl = sslBuilder.build();

    PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT));        

    CloseableHttpAsyncClient clientHttps = HttpAsyncClientBuilder.create()
            .setConnectionManager(cm)    
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
            .setSSLContext(ssl)
            .build();

    RequestConfig.Builder b = RequestConfig.custom();        
    b.setProxy(new HttpHost("proxyHost", proxyPort));
    RequestConfig rc = b.build();

    clientHttps.start();

    HttpRequestBase req = new HttpPost("https://someurl");
    ((HttpEntityEnclosingRequestBase)req).setEntity(new StringEntity("somestring"));
    req.setConfig(rc);

    clientHttps.execute(req, new FutureCallback<HttpResponse>() {

        @Override
        public void failed(Exception ex) {
            System.out.println(ex);
        }

        @Override
        public void completed(HttpResponse result) {
            System.out.println(result);                
        }

        @Override
        public void cancelled() {
            System.out.println("Cancelled");                
        }
    });    

当使用 javax.net.ssl.HttpsURLConnection 实现这个时,它有效(如果需要,我可以附上相关代码)。

编辑

根据@ben75的回答,我终于把运行变成了下面的代码

System.setProperty("javax.net.debug", "ssl,handshake");
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");

KeyStore ts = KeyStore.getInstance("JKS");
ts.load(loadStream("C:/TrustStore/cacerts"), "trustpass".toCharArray());
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(loadStream("C:/KeyStore/SSL/keystore.SomeKey"), "keypass".toCharArray());

SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(ts).loadKeyMaterial(ks, "somekey".toCharArray()).setSecureRandom(new SecureRandom());        
SSLContext ssl = sslBuilder.build();

SSLIOSessionStrategy s = new SSLIOSessionStrategy(ssl, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
RegistryBuilder<SchemeIOSessionStrategy> rb = RegistryBuilder.create();
rb.register("https", s).register("http", NoopIOSessionStrategy.INSTANCE);
PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT), rb.build());       

CloseableHttpAsyncClient clientHttps = HttpAsyncClientBuilder.create()
        .setConnectionManager(cm)
        .build();

RequestConfig.Builder b = RequestConfig.custom();        
b.setProxy(new HttpHost("proxyHost", proxyPort));
RequestConfig rc = b.build();

clientHttps.start();

HttpRequestBase req = new HttpPost("https://someurl");
((HttpEntityEnclosingRequestBase)req).setEntity(new StringEntity("somestring"));
req.setConfig(rc);

clientHttps.execute(req, new FutureCallback<HttpResponse>() {

    @Override
    public void failed(Exception ex) {
        System.out.println(ex);
    }

    @Override
    public void completed(HttpResponse result) {
        System.out.println(result);                
    }

    @Override
    public void cancelled() {
        System.out.println("Cancelled");                
    }
});    

(我 运行 最近(在 Android 上)遇到了非常相似的问题,但我猜你犯了和我一样的错误。)

当您显式设置连接管理器时:builder.setConnectionManager(cm) sslContext 被忽略。

您可以做的是在 PoolingNHttpClientConnectionManager 中注入您的 SSLContext。

为此,您可以使用此构造函数: PoolingNHttpClientConnectionManager(org.apache.http.nio.reactor.ConnectingIOReactor ioreactor, Registry iosessionFactoryRegistry)

使用 iosessionFactoryRegistry 包含 SSLIOSessionStrategy 使用您的 SSLContext

构建

这是一个工作示例:

public SSLContext getSSLContext() {
    final TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    try {
        final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();
        sslContext.getServerSessionContext().setSessionCacheSize(1000);
        return sslContext;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
    }
    return null;
}

public Registry<SchemeIOSessionStrategy> getSSLRegistryAsync() {
    return RegistryBuilder.<SchemeIOSessionStrategy>create()
            .register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", new SSLIOSessionStrategy(
                    getSSLContext(), null, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)).build();
}

public PoolingNHttpClientConnectionManager getPoolingNHttpClientConnectionManager() {
    try {
        final PoolingNHttpClientConnectionManager connectionManager =
                new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT), getSSLRegistryAsync());
        connectionManager.setMaxTotal(connectionPoolMax);
        connectionManager.setDefaultMaxPerRoute(connectionPoolMaxPerRoute);

        return connectionManager;
    } catch (IOReactorException e) {
    }
    return null;
}

public RequestConfig getRequestConfig() {
    return RequestConfig.custom()
            .setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout)
            .setConnectionRequestTimeout(socketTimeout)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
            .build();
}

public CloseableHttpAsyncClient getHttpAsyncClient() {
    final CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom()
            .setConnectionManager(getPoolingNHttpClientConnectionManager())
            .setDefaultRequestConfig(getRequestConfig())
            .build();
    return httpAsyncClient;
}

我在异步模式下的例子:

     try {
         SSLContext sslContext = getSSLContext(X509Cert);

         CloseableHttpAsyncClient httpAsyncClient = getHttpAsyncClient(sslContext,HTTP_CLIENT_MAX_POOL_CONNECTIONS,HTTP_CLIENT_MAX_PER_ROUTE_CONN);
         setHttpAsyncClient(httpAsyncClient);


    } catch (Exception e) {
        LOG.error("Generic SSL Error Adapter: {} - {}", e.getMessage(), e.getLocalizedMessage());
    }

}


private SSLContext getSSLContext(X509CertificateValidator trustStrategy) {
    try {
        final SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(null, trustStrategy)
                .build();
        sslContext.getServerSessionContext().setSessionCacheSize(1000);
        return sslContext;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        LOG.error("SSL Context creation error: {} - {}", e.getMessage(), e.getLocalizedMessage());
    }
    return null;
}


private Registry<SchemeIOSessionStrategy> getSSLRegistryAsync(SSLContext sslContext) {
    Registry<SchemeIOSessionStrategy> defaultRegistry = RegistryBuilder.<SchemeIOSessionStrategy> create()
            .register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", new SSLIOSessionStrategy(sslContext, NoopHostnameVerifier.INSTANCE))
            .build();

    return defaultRegistry;

}

private PoolingNHttpClientConnectionManager getPoolingNHttpClientConnectionManager(SSLContext sslContext, int connectionPoolMax, int connectionPoolMaxPerRoute) {
    try {
        PoolingNHttpClientConnectionManager connectionManager =
                new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT), getSSLRegistryAsync(sslContext));
        connectionManager.setMaxTotal(connectionPoolMax);
        connectionManager.setDefaultMaxPerRoute(connectionPoolMaxPerRoute);
        return connectionManager;
    } catch (IOReactorException e) {
        LOG.error("NHttp Connectio Manager error: {} - {}", e.getMessage(), e.getLocalizedMessage());
    }
    return null;
}


public CloseableHttpAsyncClient getHttpAsyncClient(SSLContext sslContext, int connectionPoolMax, int connectionPoolMaxPerRoute) {
    final CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom()
            .setConnectionManager(getPoolingNHttpClientConnectionManager(sslContext, connectionPoolMax, connectionPoolMaxPerRoute))
            //.setSSLHostnameVerifier(new NoopHostnameVerifier())
            .build();
    return httpAsyncClient;
}