【发布时间】:2019-03-22 04:49:06
【问题描述】:
我正在写一个基于JDK11 HttpClient的简单REST api客户端,简单代码如下:
public class MyClass {
private static final X509TrustManager TRUST_MANAGER = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
private static HttpClient getNewHttpClient() {
int timeout = 600;
try {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, new TrustManager[]{TRUST_MANAGER}, new SecureRandom());
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
//Set SSL parameters
SSLParameters parameters = new SSLParameters();
parameters.setEndpointIdentificationAlgorithm("HTTPS");
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofMillis(timeout * 1000))
.sslContext(sslContext)
.sslParameters(parameters)
.build();
return httpClient;
} catch (Exception e) {
logger.warn("Unable to create HttpClient with disabled SSL Certificate verifying, default client will be used", e);
return HttpClient.newHttpClient();
}
}
public static void main(String[] args) {
HttpRequest requestBuilder = HttpRequest.newBuilder()
.uri(URI.create("https://somehostname.xx.xxx.net"))
.GET()
.build();
getNewHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
}
}
问题是当我尝试打开某个 SSL 域时出现错误:
原因:java.security.cert.CertificateException:找不到与 somehostname.xx.xxx.net 匹配的主题备用 DNS 名称。
我该如何解决这个问题?
【问题讨论】:
-
是的。但这对我没有帮助。如您所见,我尝试通过添加 HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true); 来禁用验证但它对JDK11的HttpClient没有影响。
-
@Andrey 您在使用 JDK
-
@Andrey,具体的用例是什么?为什么您要连接的服务器的主机名与其证书中的 CN 或 SAN 不匹配?如果这只是一个测试环境,则可以使用 -Djdk.internal.httpclient.disableHostnameVerification 禁用主机名验证,风险自负。
-
在实例化httpclient之前以编程方式禁用主机名验证
// PREVENTS HOST VALIDATIONfinal Properties props = System.getProperties();props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
标签: java java-11 java-http-client