title: Android - Obtain self-signed server certificate and add to trusted keystore
body: <p>My android application connects to an <strong>URL provided by the user</strong>. In case of HTTPS connections, if the server's certificate is issued by a CA that already exists in the Android's TrustManager, everything is fine.</p>
  
  <p>But if the server uses a self-signed certificate how can I obtain that certificate and store it in the TrustManager on first connection?</p>
  
  <p>I am using <code>OkHttp</code> library for performing network tasks. The solution that I have currently forces me to add the certificate in the application's <code>raw</code> folder during development but this will not work for the above mentioned scenario. The code that I am using currently is as below:</p>
  
  <pre><code>private KeyStore readKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
      KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  
      String password = "testPass";
  
      InputStream is = null;
  
      try {
          is = activity.getApplicationContext().getResources().openRawResource(R.raw.server_key);
          ks.load(is, password.toCharArray());
      } finally {
          if (is != null)
              is.close();
      }
  
      return ks;
  }
  
  private OkHttpClient getOkHttpClient() throws CertificateException, IOException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
  
      SSLContext sslContext = SSLContext.getInstance("SSL");
      TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  
      trustManagerFactory.init(readKeyStore());
      KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      keyManagerFactory.init(readKeyStore(), "testPass".toCharArray());
  
      sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
  
      return new OkHttpClient().setSslSocketFactory(sslContext.getSocketFactory());
  }
  </code></pre>