HttpsUrlConnection using KeyStore instead of TrustStore with WebSphere Liberty Profile

社会主义新天地 提交于 2019-12-06 23:12:28

You can load your trust store as below and set it to SSLContext which can be set into HttpsUrlConnection. As this is an example I used defaults, you should replace them with appropriate algorithms, protocol and truststore type.

        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
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!