2019. 3. 14. 10:13ㆍJAVA
JAVA에서 SSL 적용된 사이트에 접근하기 위해 HttpsURLConnection을 사용하게 됩니다.
하지만 결과 적으로 HttpsURLConnection만 사용한다 하여 접근이 되지 않는 현상이 발생합니다.
String htmlUrl = "https://test.domain.co.kr";
HttpURLConnection conn = (HttpURLConnection) new URL(htmlUrl).openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
단순이 이렇게 HttpURLConnection를 사용할 경우 아래와 같은 오류를 발생 시킨다.
Exception in thread "main" 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
위의 오류는 해당 사이트에 SSL 인증서가 신뢰하는 기관 인증서가 없거나 SSL/TLS암호화 버전이 맞지 않는 경우 발생한다고 한다.
인터넷을 찾아 보면 Client에도 KeyStore를 만들어 주어 해결하는 방법이 있다고는 하나 모든 Client 에 설치하는건 좀 무리가 있다고 본다.
하지만 프로그램을 하다 보면 반드시 접근해야 하는 경우가 생긴다.
그래서 유효하지 않은 SSL 인증서를 사용하는 서버에 접근하도록 HttpURLConnection 를 설정을 해야 한다.
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line = null;
try {
String htmlUrl = "https://test.domain.co.kr";
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection) new URL(htmlUrl).openConnection();
InputStream is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (NoSuchAlgorithmException | IOException | KeyManagementException e) {
e.printStackTrace();
}
System.out.println(sb.toString());
'JAVA' 카테고리의 다른 글
PNG 이미지 배경 투명하게 처리 (0) | 2020.02.03 |
---|---|
[JAVA] LIST형 Remove 하기 (1) | 2019.04.16 |
[JAVA] 자동리소스 닫기 (2) | 2018.08.02 |
JSON 사용하기 (0) | 2013.06.21 |