SSL ignore - URL Connection - File Download [1]
URL Connection을 이용한 File Download [1]에서는, Stream을 이용하여 진행할 것이다.
URL Connection을 이용한 File Download [2]에서는, Resource를 이용하여 진행할 것이다.
URL Connection을 이용한 일종의 GateWay 역할을 담당하는 서비스를 구축해보고자 한다. 최종적으로는 URL Connection으로 특정 URL의 data를 읽어와, File Download를 JAVA가 대신하도록 할 것이다. 포스팅을 쓰는 까닭은, 필자가 해당 업무를 진행하며 기본적으로 URL Connection을 사용하는 방법부터, 해당 URL의 자체 SSL 인증으로 인해 JAVA가 "안해" 하는 것을 회피하는 방법까지... 한 번에 볼 수 있는 곳이 없었기 때문이다. 역시 인간은 귀찮음에서 발전을 이룩하는 것 같다.
[1] SSL ignore
HttpsURLConnection으로 통신을 할 때, 연결을 시도한 URL에서 인증되지 않은(홈페이지가 자체적으로 적용한) SSL 인증서를 맞닥뜨릴 경우, JAVA가 "안해. 이거 이상해." 라면서 Exception을 뱉어버린다. 부디 이 글을 읽는 독자들은 필자처럼 해당 홈페이지의 SSL 인증서를 추출하고, jre / lib / security 디렉토리 내 JAVA Certs에 인증 Key 추가를 하려는 뻘짓은 하지 않기를 바란다. 하단의 간단한 메소드를 생성해주도록 하자.
/** URL Connection SSL ignore **/
public static TrustManager[] createTrustManagers() {
TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) { }
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) { }
public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; }
}};
return trustAllCerts;
}
위에서 사용된 X509 어쩌구 하는 친구들은, javax.net.ssl 패키지가 제공하는 친구들이다. 필자도 이것저것 긁어다가 삽질을 하던 중 발견한 방법이다. 하단의 출처에 남겨두었다. 개인적으로 한글 참조 링크만 보는 것이 정신 건강에 이롭다.
[2] HttpsURLConnection
HttpsURLConnection에 대해 먼저 설명을 하자면... HttpURLConnection을 상속받는 javax.net.ssl의 클래스이다. HttpURLConnection에 대해 설명을 하자면, URLConnection을 상속받는 java.net의 클래스이다. 더 자세하고 알고 싶다면, 하단의 출처에 기록된 갓대희님의 블로그를 참고하자. 정말 이해하기 쉽게, 그리고 잘 정리해주셨다. URLConnection을 그대로 사용해도 되지만, 필자는 이것저것 테스트를 하다보니 HttpsURLConnection가 지원하는 메소드가 필요했었고, 해당 게시물에는 사실 URLConnection만 사용해도 되긴하다... 아무튼, HttpsURLConnection으로 통신을 시도해보자.
/** HTTPsURLConnection 진행(URL Connection SSL ignore 적용) **/
public static void main(String[] args) {
try {
// SSL ignore 설정
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, createTrustManagers(), new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = (hostname, session) -> true;
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
// test URL 설정
String urlStr = "https://installer-whale.pstatic.net/downloads/banner/RydDy7/WhaleSetup.exe";
// HttpsURLConnection 설정
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Cache-Control", "no-cache");
// HttpsURLConnection 결과값 확인
System.out.println("responseCode : " + conn.getResponseCode());
} catch (Exception e) {
System.out.println(e);
}
}
Test로 사용한 URL은 초록 검색창의 고래 브라우저 다운로드 링크이다. 위의 소스를 실행하면 HttpsURLConnection의 결과값을 확인할 수 있다.
[3] File Download
File Download를 위해 Stream을 사용할 것이다. java.io 패키지가 지원하는 InputStream 및 FileOutputStream 두 개를 혼합하여 사용할 것이며, HttpsURLConnection을 통하여 읽어온 data를 Stream을 통해 다운로드 받을 것이다. 위의 예제 코드에 추가로 작성하도록 하자.
/** HTTPsURLConnection 진행(URL Connection SSL ignore 적용) **/
public static void main(String[] args) {
try {
.
.
중략
.
.
// buffer 설정
int bytesRead = -1;
byte[] buffer = new byte[4096];
// stream 설정
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream("C:\\Users\\test\\Downloads\\WhaleSetup.exe");
// download
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("responseCode : " + conn.getResponseCode());
} catch (Exception e) {
System.out.println(e);
}
}
FileOutPutStream을 이용하여 지정한 경로(C:/Users/test/Downloads)에 지정한 파일명(WhaleSetup.exe)으로 다운로드를 시켜준다.
[ 출처 ]
URLConnection 기본 개념 : https://goddaehee.tistory.com/268
SSL ignore(영문 참조) : https://nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/
SSL ignore(한글 참조) : https://boxfoxs.tistory.com/374
HttpsURLConnection : https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/HttpsURLConnection.html
'Java > Default' 카테고리의 다른 글
JAVA SSL ignore - URL Connection - File Download [2] Resource (0) | 2021.12.17 |
---|---|
JAVA 반복문 / for... 또는 foreach 문 (0) | 2021.10.27 |
JAVA 현재 일자 파악 / Data (0) | 2021.08.23 |
JAVA 조건문 / if... else... else if... (0) | 2021.08.23 |