向OkHttp客户端添加自定义证书

时间:2018-11-14 15:52:40

标签: java android ssl okhttp

我正在尝试制作Android应用程序,可以在其中获取和解析HTML(从没有API的网站)。我正在使用OkHttp。该站点具有不受信任(但有效)的证书。我得到了:

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

我已经设置了官方方式(https://developer.android.com/training/articles/security-ssl#java),现在需要将其与OkHttpClient链接。

我尝试过

    OkHttpClient client = new OkHttpClient;

    OkHttpClient.Builder builder = client.newBuilder();
    builder.sslSocketFactory(sslcontext.getSocketFactory()).build();

但是它不起作用,也已弃用。 谢谢

3 个答案:

答案 0 :(得分:4)

有关添加已知受信任证书的信息,请参见此文档示例

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java

  public CustomTrust() {
    X509TrustManager trustManager;
    SSLSocketFactory sslSocketFactory;
    try {
      trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, new TrustManager[] { trustManager }, null);
      sslSocketFactory = sslContext.getSocketFactory();
    } catch (GeneralSecurityException e) {
      throw new RuntimeException(e);
    }

    client = new OkHttpClient.Builder()
        .sslSocketFactory(sslSocketFactory, trustManager)
        .build();
  }

答案 1 :(得分:2)

您需要使用未弃用的sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

使用此变量(它将创建不验证证书链的信任管理器):

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[]{};
        }
    }
};

并通过以下方式传递到sslSocketFactory()

builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);

还将其应用于验证每个主机:

builder.hostnameVerifier(new HostnameVerifier() {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
});

答案 2 :(得分:1)

OkHttp 4.7.1仅支持特定的不安全主机进行开发

https://square.github.io/okhttp/changelog/

https://github.com/square/okhttp/blob/482f88300f78c3419b04379fc26c3683c10d6a9d/samples/guide/src/main/java/okhttp3/recipes/kt/DevServer.kt

  val clientCertificates = HandshakeCertificates.Builder()
      .addPlatformTrustedCertificates()
      .addInsecureHost(server.hostName)
      .build()

  val client = OkHttpClient.Builder()
      .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)
      .build()