使用Hoverfly-java在单元测试中模拟Web服务,并使用HttpClient作为Web客户端,发现使用useSystemProperties()
正确传播了hoverfly代理设置,但是我仍然遇到TLS错误:未知证书,我必须使用以下命令手动将证书添加到密钥库
wget https://raw.githubusercontent.com/SpectoLabs/hoverfly/master/core/cert.pem
sudo $JAVA_HOME/bin/keytool -import -alias hoverfly -keystore $JAVA_HOME/jre/lib/security/cacerts -file cert.pem
我需要在没有以上两个命令的情况下添加Hoverfly SSL上下文,我尝试过:
CloseableHttpClient httpClient = httpClientBuilder.useSystemProperties().setSSLContext(SomeTestClass.hoverflyRule.getSslConfigurer().getSslContext()).build();
但仍然存在TLS错误,有什么想法吗?
我知道可以使用
ProcessBuilder
从Java代码运行以上两个命令,但这会带来安全问题,因为它需要sudo访问和不需要的漏洞(这也行不通)。 最佳答案
联系Hoverfly support后,我的工作如下
CloseableHttpClient httpClient = HttpClients.custom()
//.setConnectionManager(poolingConnectionManager) //this causes TLS errors so I commented it out until this final issue is solved.
.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
.setDefaultRequestConfig(requestConfig)
.setDefaultCredentialsProvider(credsProvider)
.setDefaultHeaders(headers)
.useSystemProperties()
.build();
我在使用
setConnectionManager()
时仍然有问题(它再次导致TLS错误),这些是我需要为新创建的HttpCleint
添加的设置PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
poolingConnectionManager.setMaxTotal(1000);
poolingConnectionManager.setDefaultMaxPerRoute(1000);
更新
解决的问题,在搜索并联系Hoverfly支持后,我发现similar problem,我使用sol解决了它
private PoolingHttpClientConnectionManager getPoolingHttpClientConnectionManager() {
SSLConnectionSocketFactory sslsocketFactory = null;
try {
sslsocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(), new DefaultHostnameVerifier());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslsocketFactory)
.register("http", PlainConnectionSocketFactory.INSTANCE)
.build();
PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
poolingConnectionManager.setMaxTotal(1000);
poolingConnectionManager.setDefaultMaxPerRoute(1000);
// Used these settings instead of constructor parameters (long timeToLive, TimeUnit timeUnit)
poolingConnectionManager.closeIdleConnections(30, TimeUnit.SECONDS);
return poolingConnectionManager;
}
我希望Hoverfly可以解决所有这些麻烦。