Retrofit2でオレオレ証明書なサーバにアクセスすると、
こんなエラーが出る。その時の対処方法の備忘録。
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:361)
ソース
こんな感じ。Retrofit2の内部で利用しているOkHttpClientのカスタマイズし、
安全でない証明書でも許可するように変更する。
開発中など一時的な感じで使う。
import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.security.cert.CertificateException; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; public class ApiClientFactory { // ApiClientを生成する処理 public ApiClient getApiClient(String baseUrl) { return new Retrofit.Builder() .baseUrl(baseUrl) .client(getHttpClient()) .build() .create(ApiClient.class); } private OkHttpClient getHttpClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // return new OkHttpClient.Builder() // 通常のBuilderの代わりに、カスタマイズしたBuilderを使う return getUnsafeOkHttpClient() .readTimeout((15 * 1000), TimeUnit.MILLISECONDS) .writeTimeout((20 * 1000), TimeUnit.MILLISECONDS) .connectTimeout((20 * 1000), TimeUnit.MILLISECONDS) .addInterceptor(interceptor) .build(); } private static OkHttpClient.Builder getUnsafeOkHttpClient() { try { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); return builder; } catch (Exception e) { throw new RuntimeException(e); } } }