我尝试使用单个客户端端点创建多个异步HTTP连接我尝试了Apache site中提供的多路复用示例
代码段如下,
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
.setSoTimeout(Timeout.ofSeconds(5))
.build();
final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(
HttpVersionPolicy.FORCE_HTTP_2, H2Config.DEFAULT, null, ioReactorConfig);
client.start();
final HttpHost target = new HttpHost("localhost", 7070, "https");
final Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
final AsyncClientEndpoint endpoint = leaseFuture.get(30, TimeUnit.SECONDS);
try {
final String[] requestUris = new String[] {"/test.html"};
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri: requestUris) {
final SimpleHttpRequest request = SimpleHttpRequest.get(target, requestUri);
endpoint.execute(
SimpleRequestProducer.create(request),
SimpleResponseConsumer.create(),
new FutureCallback<SimpleHttpResponse>() {
@Override
public void completed(final SimpleHttpResponse response) {
latch.countDown();
System.out.println(requestUri + "->" + response.getCode());
System.out.println(response.getBody());
}
@Override
public void failed(final Exception ex) {
latch.countDown();
System.out.println(requestUri + "->" + ex);
}
@Override
public void cancelled() {
latch.countDown();
System.out.println(requestUri + " cancelled");
}
});
}
latch.await();
} finally {
endpoint.releaseAndReuse();
}
System.out.println("Shutting down");
client.shutdown(ShutdownType.GRACEFUL);
此示例适用于具有有效证书的站点,但如果我想尝试证书已过期/自签名的站点,则会引发以下异常
javax.net.ssl.SSLHandshakeException:常规SSLEngine问题javax.net.ssl.SSLHandshakeException:一般SSLEngine问题在 sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1478)at at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:535) 在 sun.security.ssl.SSLEngineImpl.writeAppRecord(SSLEngineImpl.java:1214) 在sun.security.ssl.SSLEngineImpl.wrap(SSLEngineImpl.java:1186)at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:469)at org.apache.hc.core5.reactor.ssl.SSLIOSession.doWrap(SSLIOSession.java:256) 在 org.apache.hc.core5.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:294) 在 org.apache.hc.core5.reactor.ssl.SSLIOSession.isAppInputReady(SSLIOSession.java:502) 在 org.apache.hc.core5.reactor.InternalDataChannel.onIOEvent(InternalDataChannel.java:112) 在 org.apache.hc.core5.reactor.InternalChannel.handleIOEvent(InternalChannel.java:50) 在 org.apache.hc.core5.reactor.SingleCoreIOReactor.processEvents(SingleCoreIOReactor.java:173) 在 org.apache.hc.core5.reactor.SingleCoreIOReactor.doExecute(SingleCoreIOReactor.java:123) 在 org.apache.hc.core5.reactor.AbstractSingleCoreIOReactor.execute(AbstractSingleCoreIOReactor.java:80) 在 org.apache.hc.core5.reactor.IOReactorWorker.run(IOReactorWorker.java:44) 在java.lang.Thread.run(Thread.java:748)引起: javax.net.ssl.SSLHandshakeException:常见的SSLEngine问题 sun.security.ssl.Alerts.getSSLException(Alerts.java:192)at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1728)at at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:304)at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1514) 在 sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216) 在sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)at at sun.security.ssl.Handshaker $ 1.run(Handshaker.java:966)at sun.security.ssl.Handshaker $ 1.run(Handshaker.java:963)at java.security.AccessController.doPrivileged(Native Method)at sun.security.ssl.Handshaker $ DelegatedTask.run(Handshaker.java:1416) 在 org.apache.hc.core5.reactor.ssl.SSLIOSession.doRunTask(SSLIOSession.java:274) 在 org.apache.hc.core5.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:331) ... 8更多引起:sun.security.validator.ValidatorException:PKIX 路径构建失败: sun.security.provider.certpath.SunCertPathBuilderException:无法 找到所请求目标的有效证书路径 sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:397) 在 sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:302) 在sun.security.validator.Validator.validate(Validator.java:260)at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324) 在 sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:281) 在 sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:136) 在 sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1501) ... 16更多引起: sun.security.provider.certpath.SunCertPathBuilderException:无法 找到所请求目标的有效证书路径 sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141) 在 sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126) 在java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280) 在 sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392) ......还有22个
我尝试过: 我创建了一个套接字工厂,它信任所有证书,并尝试在connectionManager中设置但是创建了一个CloseableHttpClient,我认为哪个不能用于异步多路复用,代码如下
SSLContext sslContext = SSLContextBuilder
.create()
.loadTrustMaterial(new TrustSelfSignedStrategy())
.build();
// we can optionally disable hostname verification.
// if you don't want to further weaken the security, you don't have to include this.
HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
// create an SSL Socket Factory to use the SSLContext with the trust self signed certificate strategy
// and allow all hosts verifier.
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create().register("https", connectionFactory).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
CloseableHttpClient build = HttpClients.custom().setConnectionManager(cm).build();
如果有任何方法或变通方法可以忽略MinimalHttpAsyncClient中的自签名证书,请告诉我。
答案 0 :(得分:1)
首先,配置应用程序使用的SSL上下文。如果你绝对不得不让它只信任特定的自签名证书,而不是不加区分地信任所有证书,这是非常明智的
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(new TrustAllStrategy())
.build();
使用给定的SSL上下文创建自定义连接管理器
final PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder.create()
.setTlsStrategy(new H2TlsStrategy(sslContext, NoopHostnameVerifier.INSTANCE))
.build();
使用给定的连接管理器
创建自定义HttpAsyncClient
实例
final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(
HttpVersionPolicy.FORCE_HTTP_2,
H2Config.DEFAULT,
null,
ioReactorConfig,
connectionManager);
或者,如果您只关心HTTP / 2并且不需要具有HTTP / 1.1回退的客户端,请考虑使用HTTP / 2优化实现。最小的实现将提供基本的消息传输功能(无状态管理,无身份验证,无缓存,无自动重定向),并且开销最小。
final MinimalHttp2AsyncClient h2ClientMinimal = HttpAsyncClients.createHttp2Minimal(
H2Config.DEFAULT,
ioReactorConfig,
new H2TlsStrategy(sslContext, NoopHostnameVerifier.INSTANCE));
全功能的实现将提供功能齐全的HTTP / 2传输,其中包含经典HttpClient
支持的所有功能,唯一的例外是透明内容解压缩:
final HttpAsyncClient h2Client = HttpAsyncClients.customHttp2()
.setIOReactorConfig(ioReactorConfig)
.setTlsStrategy(new H2TlsStrategy(sslContext, NoopHostnameVerifier.INSTANCE))
.build();
希望这有帮助