我想使用Java REST API(RestHighLevelClient)通过HTTPS与Elasticsearch 5.6服务器通信。但是,服务器的证书是自签名的,当我尝试连接时,它将引发SSLHandshakeException。
有没有一种方法可以配置REST客户端以接受自签名证书?
我使用自定义Java密钥库来完成此工作。这是我的代码:
CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); final SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(new File("my_keystore.jks"), keystorePassword.toCharArray(), new TrustSelfSignedStrategy()) .build(); RestClient client = RestClient.builder(new HttpHost(host, port, scheme)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder .setDefaultCredentialsProvider(credentialsProvider) .setSSLContext(sslContext) ).build();
为了创建密钥库,我通过Firefox下载了该域的证书,并使用:
keytool -import -v -trustcacerts -file my_domain.crt -keystore my_keystore.jks -keypass password -storepass password