SSL ignore - URL Connection - File Download [2]
URL Connection을 이용한 File Download [1]에서는, Stream을 이용하여 진행하였다.
URL Connection을 이용한 File Download [2]에서는, Resource를 이용하여 진행할 것이다.
이전에 작성한 URL Connection을 이용한 File Download [1]을 참고하도록 하자. 해당 게시물을 보면 다음과 같이 구성이 되어있음을 알 수 있다.
- SSL ignore
- HttpsURLConnection
- File Download
1번과 2번까지는 같은 내용을 다룰 것이다. File Download 방식을 변경할 것이기에, 이전 포스팅에서 1번과 2번까지 테스트를 마치고 아래의 내용을 보면 좋을 듯 하다. 그래도 귀찮은 분들을 위해, 이전 포스팅에서 진행한 source를 하단에 첨부하도록 하겠다.
[1] SSL ignore Source
/** 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;
}
[2] HttpsURLConnection Source
/** 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은 초록 검색창의 고래 브라우저 다운로드 링크이다)
[3] File Download
File Download를 위해 지난번에는 Stream을 사용하였다. 이번에는 Resource를 사용해보도록 하겠다. 위의 예제 코드에 추가로 작성하도록 하자.
/** HTTPsURLConnection 진행(URL Connection SSL ignore 적용) **/
public static void main(String[] args) {
// try 내 사용될 변수 및 객체 선언
Resource resource = null;
String contentType = null;
String fileName = "WhaleSetup.exe";
try {
.
.
중략
.
.
// resource 및 contentType 설정
resource = new UrlResource(conn.getURL().toURI());
contentType = conn.getContentType();
// ResponseEntity 설정
ResponseEntity
.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.body(resource);
System.out.println("responseCode : " + conn.getResponseCode());
} catch (Exception e) {
System.out.println(e);
}
}
위의 소스를 실행하면 HttpsURLConnection의 결과값을 확인할 수 있다.
주의
jUnit 및 void 형식으로 method를 구성하거나 테스트를 진행하면, 결과값만 출력되고 실제로 다운로드가 진행되지 않을 것이다. MVC 형태를 구성할 때
- Service에서는 ResponseEntity<Resource> 형태로 return 값을 지정 해주고
- Controller에서는 ResponseEntity<Resource> 형태로 Service로 부터 값을 받아오고
- 화면단에서는 받아온 return 값을 window.location = url 형태로 띄워주면 된다.
[ 출처 ]
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 [1] Stream (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 |