title: How to programmatically add certificates to a truststore and use that also for verifying server authentication
body: <p>I my app I want to use a https connection to a user-specified server which uses a self-signed certificate. What I gathered by now is, that</p>
  
  <ul>
  <li>self signed certificates are rejected (as expected)</li>
  <li>the android keystore/truststore is not used for apps, so apps have to build and use their own truststore,</li>
  <li>there's a "keytool" in the JDK to build a truststore that can be supplied to the app as a resource, which however is not a solution since I do not know the server (and its certificate beforehand)</li>
  </ul>
  
  <p>Since the https server is user specified, I do not know the server's certificate beforehand and thus want to add the server certificate programmatically to the app's truststore (by showing the certificate to the user and have him accept it). Once added to the truststore, the app shall use that truststore to authenticate the server.</p>
  
  <p>I do NOT want to simply accept every self-signed certificate without the user checking the fingerprint as some examples on the web suggest.</p>
  
  <p>Now the problem is that I'm completely new to Java and Android and am struggling to understand the inner workings of the AndroidHttpClient or DefaultHttpClient. I have basic HTTP working in my app, but haven't found any example on how to actually ADD certificates to a truststore inside the app on demand of the user.</p>
  
  <p>Does anybody know how to achieve that or knows a working example that I can look at?</p>
  
  <p>Any hints are appreciated. Thanks.</p>
  
  <p>EDIT: Found the Solution in the <a href="https://github.com/k9mail/k-9/blob/master/src/com/fsck/k9/mail/store/TrustManagerFactory.java" rel="noreferrer">TrustManagerFactory.java class of K9 Mail</a>. I suggest to have a look at it if you're having the same question.</p>