「Java」 HttpsURLConnection で HTTPS 通信する ( 信頼性のチェックなし )
HttpsURLConnection で HTTPS 通信するサンプル書いてみたので、メモしておきます。
ひとまず、今回は X509TrustManager の実装クラス ( NonAuthentication ) を作って、証明書の信頼性チェックはしない感じにしています。
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.List; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.X509TrustManager; public class Test { public static void main(String[] args) throws Exception { SSLSocketFactory factory = null; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new NonAuthentication[] { new NonAuthentication() }, null); factory = ctx.getSocketFactory(); URL url = new URL("https://example.com/hello.html"); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(factory); System.out.println("----- Headers -----"); Map<String, List<String>> headers = con.getHeaderFields(); for (String key : headers.keySet()) { System.out.println(key + ": " + headers.get(key)); } System.out.println(); System.out.println("----- Body -----"); BufferedReader reader = new BufferedReader(new InputStreamReader( con.getInputStream())); String body; while ((body = reader.readLine()) != null) { System.out.println(body); } reader.close(); con.disconnect(); } } class NonAuthentication implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }
・JSSE Reference Guide
http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#HttpsURLConnection
・HttpsURLConnection (Java Platform SE 8 )
https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/HttpsURLConnection.html
・X509TrustManager (Java Platform SE 8 )
https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/X509TrustManager.html
以上です。