Ⅰ. はじめに
オレオレ証明書などは以下のエラーを吐いて弾かれてしまいます。
デバッグ時など、とりあえず全部許可したいときのやり方です。
Exception in thread "main" javax.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
Ⅱ. プログラム
import okhttp3.*; import javax.net.ssl.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class Main { static class MyX509TrustManager implements X509TrustManager { public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } private static String okHttpGet() throws Exception { // リクエストを作成する Request request = new Request.Builder() .url("https://example.com/") .get() .build(); // OkHttpClient の Bulider を作成する OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); // proxyを設定する clientBuilder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8008))); // MyX509TrustManager を割り当てる // MyX509TrustManager は全ての証明書を許可するようにしている SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { new MyX509TrustManager() }, new java.security.SecureRandom()); clientBuilder.sslSocketFactory(sslContext.getSocketFactory(), new MyX509TrustManager()); OkHttpClient client = clientBuilder.build(); // GET する Response response = client.newCall(request).execute(); return response.body().string(); } public static void main(String[] args) throws Exception{ String str = okHttpGet(); System.out.println(str); } }