我们在WebSphere Liberty Profile中的WebSphere TAI中使用HttpsUrlConnection来连接到安全服务器。我遇到了很多SSL证书错误的问题,直到我发现它在WLP密钥库中寻找签名者证书,而不是WLP信任库或JVM信任库。代码设置中没有任何内容,它必须是默认值。但我很困惑,因为当我们在其他代码中使用HTTP客户端时,它使用JVM的信任库。
如何让HttpsUrlConnection使用WLP或JVM信任库,而不是密钥库?
答案 0 :(得分:1)
您可以按如下所示加载信任存储,并将其设置为SSLContext,可以将其设置为HttpsUrlConnection。由于这是我使用默认值的示例,您应该使用适当的算法,协议和信任库类型替换它们。
try (FileInputStream truststoreFile = new FileInputStream("path/to/your/truststore.jks")) {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
char[] trustorePassword = "<truststorePassword".toCharArray();
truststore.load(truststoreFile, trustorePassword);
trustManagerFactory.init(truststore);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
KeyManager[] keyManagers = {};//if you have key managers;
sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), new SecureRandom());
URL httpsUrl = new URL("<your https url>");
URLConnection urlConnection = httpsUrl.openConnection();
} catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
//handle exception
} catch (KeyManagementException e) {
//handle exception
}