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

前端 未结 2 1467
滥情空心
滥情空心 2021-02-03 10:48

There are three hosts that an android app do the authentication and authorization. Final host is the REST API. For the first time using Oauth authentication and authorization pr

2条回答
  •  后悔当初
    2021-02-03 11:24

    1. Paste your cert.pem in raw folder

    2. Create a method

      private SSLSocketFactory getSSLSocketFactory(){
          try {
              CertificateFactory cf;
              cf = CertificateFactory.getInstance("X.509");
      
              Certificate ca;
              InputStream cert = context.getResources().openRawResource(R.raw.cert);
              ca = cf.generateCertificate(cert);
              cert.close();
      
              String keyStoreType = KeyStore.getDefaultType();
              KeyStore keyStore   = KeyStore.getInstance(keyStoreType);
              keyStore.load(null, null);
              keyStore.setCertificateEntry("ca", ca);
      
              String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
              TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
              tmf.init(keyStore);
      
              SSLContext sslContext = SSLContext.getInstance("TLS");
              sslContext.init(null, tmf.getTrustManagers(), null);
      
              return sslContext.getSocketFactory();
      
          }
          catch (Exception e){
              return null;
          }
      }
      
    3. Call like this

      final OkHttpClient client = new OkHttpClient();
       //pass getSSLSocketFactory() in params
       client.setSslSocketFactory(getSSLSocketFactory());
      
       String appURl = context.getString(R.string.apis_app_url);
      
       final RestAdapter restAdapter = new RestAdapter.Builder()
               .setEndpoint(appURl).setClient(new OkClient(client)).
                       build();
      

提交回复
热议问题