Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to make Android app, where I can get and parse HTML (from site which doesnt have API). I am using OkHttp. The site has untrusted (but valid) certificate. I am getting:

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

I've already set up the official way (https://developer.android.com/training/articles/security-ssl#java) and now I need to link it with OkHttpClient.

I tried

    OkHttpClient client = new OkHttpClient;

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

But it doesnt work, and also it is deprecated. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
675 views
Welcome To Ask or Share your Answers For Others

1 Answer

See this documented example for adding a known trusted certificate

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();
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...