JAVA
java https url 인증서 없이 호출
질주하는구
2020. 9. 1. 16:11
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.Charset; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class TestData { public static void main(String[] args) throws Exception { String url = ""; String urlParameters = ""; URL obj = new URL(url); ignoreSsl(); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setConnectTimeout(10000); //컨텍션타임아웃 10초 con.setReadTimeout(5000); //컨텐츠조회 타임아웃 5초 con.setDoOutput(true); //항상 갱신된내용을 가져옴. DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); Charset charset = Charset.forName("UTF-8"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(),charset)); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } public static void ignoreSsl() throws Exception{ HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv); } public 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; } } }
반응형