반응형
자바로 HttpsURLConnection을 사용하여 https 사이트에 connect 하면 오류가 난다.
이 경우에는 SSL을 무시하여 우회하도록 하는 코드를 작성하여야 한다.
먼저, 해당 URL이 https 인지 판별하는 코드를 썼다.
1 2 3 4 5 6 | URL aURL = new URL(url); if (aURL.getProtocol().equals("https")) { //해당 url이 https이면 resultData = httpsGet(url); //ssl인증서를 무시하는 함수를 호출한다. logger.debug("https resultData: {}" , resultData); } | cs |
httpsGet함수 - 다른 부분은 http 호출방식과 유사하나 ignoreSSL 처럼 connection 전에 처리해줘야할 사항들이 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public static String httpsGet(String strURL) throws Exception { URL url = null; HttpsURLConnection con = null; String ret = new String(); try { url = new URL(strURL); ignoreSsl(); con = (HttpsURLConnection)url.openConnection(); BufferedReader br = null; br = new BufferedReader(new InputStreamReader(con.getInputStream())); String input = null; while ((input = br.readLine()) != null){ ret += input; } br.close(); } catch (IOException e) { ExceptionUtil.getStackTrace(e); } finally { if (con != null) { con.disconnect(); } } return ret; } | cs |
ignoressl()함수
1 2 3 4 5 6 7 8 9 | public static void ignoreSsl() throws Exception{ HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) return true; } }; trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv); } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | private static void trustAllHttpsCertificates() throws Exception { TrustManager[] trustAllCerts = new TrustManager[1]; TrustManager tm = new miTM(); trustAllCerts[0] = tm; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } static class miTM implements TrustManager,X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public boolean isServerTrusted(X509Certificate[] certs) { return true; } public boolean isClientTrusted(X509Certificate[] certs) { return true; } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { return; } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { return; } } | cs |
핵심은 connection 전에 호출 처리를 해줘야 오류가 나지 않는다.
반응형
'개발공부 > 개발TIP' 카테고리의 다른 글
Java - List<> for loop 이용하여 객체 삭제 시 주의할점 (0) | 2020.01.21 |
---|---|
Tomcat 설치 시 유의할점 -server.xml (0) | 2020.01.21 |
tar 상대경로로 압축 및 절대경로로 압축된 tar 풀기 (0) | 2018.09.05 |
String, Stringbuilder, StringBuffer 차이점 (0) | 2018.08.13 |
Crontab - 배치 (0) | 2018.07.02 |