我正在尝试从Java调用Https服务,该服务需要ssl证书。 现在,我尝试调用的https服务使用以下命令
创建了一个密钥库keytool -genkey -keystore abc.jks -dname "CN=test, OU=test, O=test, L=test, ST=test, C=IN" -alias testcert -keyalg RSA -keysize 2048 -validity 365
现在,当我尝试使用上面生成的相同密钥库来调用服务时,我将获得如下异常,
avax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1731)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
我使用以下代码连接到https服务,
char []passwKey = "passwd".toCharArray();
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream("abc.jks"), passwKey);
KeyManagerFactory keyFac = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyFac.init(keyStore,passwKey);
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyFac.getKeyManagers(), null, null);
HttpsURLConnection conn = (HttpsURLConnection)new URL("https://url").openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setSSLSocketFactory(sslContext.getSocketFactory());
int responseCode = conn.getResponseCode();
System.out.println("RESPONSE: " + responseCode);