我试图接受我的证书来测试我的REST api。 为此,我试过了:
SSLContext sslcontext = SSLContexts
.custom()
.loadTrustMaterial(new File(KEYSTORE_PATH), KEYSTORE_PASSWORD,
new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient closeableHttpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
try {
HttpPost postRequest = new HttpPost(BASE_URL);
CloseableHttpResponse response = closeableHttpClient
.execute(postRequest);
// try {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
// } finally {
// response.close();
// }
} finally {
closeableHttpClient.close();
}
当我执行closeableHttpClient.execute(postRequest);
变量是:
private static final String KEYSTORE_PATH = System.getProperty("java.home")
+ "/lib/security/cacerts".replace('/', File.separatorChar);
private static final char[] KEYSTORE_PASSWORD = "changeit".toCharArray();
private static final String BASE_URL = "http://localhost:9010/api";
注意:我没有域名,我在localhost上。 如果我理解错误,那么我的SSLConnectionSocketFactory太早关闭了。但我不知道如何以及为什么。
编辑:我正在使用HTTPClient。
如果我将端口HTTP更新为HTTPS,则会收到另一个错误:javax.net.ssl.SSLPeerUnverifiedException: Host name 'localhost' does not match the certificate subject provided by the peer
答案 0 :(得分:0)
我在这里找到了解决方案:javax.net.ssl.SSLPeerUnverifiedException: Host name does not match the certificate subject provided by the peer 我的代码现在是:
SSLContext sslcontext = SSLContexts
.custom()
.loadTrustMaterial(new File(KEYSTORE_PATH), KEYSTORE_PASSWORD,
new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, NoopHostnameVerifier.INSTANCE);
final Registry<ConnectionSocketFactory> registry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http", new PlainConnectionSocketFactory())
.register("https", sslsf).build();
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
registry);
cm.setMaxTotal(100);
它正在工作但我仍在努力(理解并发现我是否可以做其他事情/更好)!谢谢