Https SSLHandshakeException..!
https로 데이터를 요구할 경우에 인증서가 만료되었거나 없을 경우 다음과 같은 Exception이 발생하게 된다.
Caused by: javax.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
이때 인증서를 다운 받거나 아니면 인증서를 무시하는 코드를 작성하면 문제는 해결이 된다.
인증서를 무시하는 방법에 대해서 알아보겠다.
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs,
String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs,
String authType) {
}
} };
//Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc
.getSocketFactory());
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String paramString,
SSLSession paramSSLSession) {
return true;
}
});
} catch (Exception e) {
}
InputStreamReader isr = null;
//Now you can access an https URL without having the certificate in the truststore
try {
URL url = new URL(
"https://requestUrl");
HttpsURLConnection con = (HttpsURLConnection) url
.openConnection();
isr = new InputStreamReader(con.getInputStream(), "utf-8");
int c;
while ((c = isr.read()) != -1) {
sb.append((char) c);
}
//System.out.println(sb.toString());
} catch (MalformedURLException e) {
out.println(e.toString());
} finally {
try {
isr.close();
} catch (Exception e) {
}
}
다음의 코드로 데이터를 받으면 문제 없이 받을 수 있다.
참 쉽다.