我正在编写一个基于 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 名称。
我怎么解决这个问题?