본문 바로가기

Languages/Java

Java-HTTPS 주소의 파일 다운로드

 

 

HTTPS 건 HTTP건 일반적인 환경에서 URL 접속은 대게 아래와 같이 사용하고 있습니다.

    URL url = new URL("https://hostname:port/file.txt");
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    // .. then download the file

 

 

하지만 HTTPS 환경에서는 server 인증서가 없거나 지정하지 않을 경우 아래와 같은 오류를 만나게 됩니다.

    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 ......... ........... ..........

 

 

그렇기 때문에 인증서가 있다면 인증서의 위치를 지정해줘야 하지만, 인증서가 없을 경우에는 아래와 같이 작성해서 사용할 수 있습니다.

    // Create a new trust manager that trust all certificates
    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) {
            }
        }
    };
    
    // Activate the new trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
    
    // And as before now you can use URL and URLConnection
    URL url = new URL("https://hostname:port/file.txt");
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    // .. then download the file

 

 

 

이 방법이 해답은 아니며, HTTPS 프로토콜을 사용한다면 서버의 인증서를 지정하는 방식을 사용하는 것을 권합니다.

 

 

출처: http://stackoverflow.com/questions/10135074/download-file-from-https-server-using-java


기타 HTTPS 파일 다운로드 예제

http://www.mkyong.com/java/java-https-client-httpsurlconnection-example/