title: Android: HTTPS (SSL) connection using HttpsURLConnection
body: <p>I have 2 apps, one is a Servlet/Tomcat Server, and the other is an Android app.</p>
  
  <p>I want to use HttpURLConnection to send and receive XML between both.</p>
  
  <p>Code:</p>
  
  <pre><code>    private String sendPostRequest(String requeststring) {
  
      DataInputStream dis = null;
      StringBuffer messagebuffer = new StringBuffer();
  
      HttpURLConnection urlConnection = null;
  
      try {
          URL url = new URL(this.getServerURL());
  
          urlConnection = (HttpURLConnection) url.openConnection();           
  
          urlConnection.setDoOutput(true);
  
          urlConnection.setRequestMethod("POST");
  
          OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
  
          out.write(requeststring.getBytes());
  
          out.flush();
  
          InputStream in = new BufferedInputStream(urlConnection.getInputStream());
  
          dis = new DataInputStream(in);
  
          int ch;
  
          long len = urlConnection.getContentLength();
  
          if (len != -1) {
  
              for (int i = 0; i &lt; len; i++)
  
                  if ((ch = dis.read()) != -1) {
  
                      messagebuffer.append((char) ch);
                  }
          } else {
  
              while ((ch = dis.read()) != -1)
                  messagebuffer.append((char) ch);
          }
  
          dis.close();
  
      } catch (Exception e) {
  
          e.printStackTrace();
  
      } finally {
  
          urlConnection.disconnect();
      }
  
      return messagebuffer.toString();
  }
  </code></pre>
  
  <p>Now, I need to use SSL to send the XMLs for security.</p>
  
  <p>First, I use Java Keytool  to generate the .keystore file.</p>
  
  <pre><code>Keytool  -keygen -alias tomcat -keyalg RSA
  </code></pre>
  
  <p>Then I put the XML Code on server.xml file of Tomcat to use SSL</p>
  
  <pre><code>&lt;Connector 
  port="8443" protocol="HTTP/1.1" SSLEnabled="true"
  maxThreads="150" scheme="https" secure="true"
  keystoreFile="c:/Documents and Settings/MyUser/.keystore"
  keystorePass="password"
  clientAuth="false" sslProtocol="TLS" 
  /&gt;
  </code></pre>
  
  <p>Then, I change it the HttpURLConnection for HttpsURLConnection </p>
  
  <pre><code>    private String sendPostRequest(String requeststring) {
  
      DataInputStream dis = null;
      StringBuffer messagebuffer = new StringBuffer();
  
      HttpURLConnection urlConnection = null;
  
      //Conexion por HTTPS
      HttpsURLConnection urlHttpsConnection = null;
  
      try {
          URL url = new URL(this.getServerURL());
  
          //urlConnection = (HttpURLConnection) url.openConnection();         
  
          //Si necesito usar HTTPS
          if (url.getProtocol().toLowerCase().equals("https")) {
  
              trustAllHosts();
  
              //Creo la Conexion
              urlHttpsConnection = (HttpsURLConnection) url.openConnection();
  
              //Seteo la verificacion para que NO verifique nada!!
              urlHttpsConnection.setHostnameVerifier(DO_NOT_VERIFY);
  
              //Asigno a la otra variable para usar simpre la mism
              urlConnection = urlHttpsConnection;
  
          } else {
  
              urlConnection = (HttpURLConnection) url.openConnection();
          }
  
  //Do the same like up
  </code></pre>
  
  <p>and add a trustAllHosts method to Trust every server (dont check for any certificate)</p>
  
  <pre><code>private static void trustAllHosts() {
  
      X509TrustManager easyTrustManager = new X509TrustManager() {
  
          public void checkClientTrusted(
                  X509Certificate[] chain,
                  String authType) throws CertificateException {
              // Oh, I am easy!
          }
  
          public void checkServerTrusted(
                  X509Certificate[] chain,
                  String authType) throws CertificateException {
              // Oh, I am easy!
          }
  
          public X509Certificate[] getAcceptedIssuers() {
              return null;
          }
  
      };
  
      // Create a trust manager that does not validate certificate chains
      TrustManager[] trustAllCerts = new TrustManager[] {easyTrustManager};
  
      // Install the all-trusting trust manager
      try {
          SSLContext sc = SSLContext.getInstance("TLS");
  
          sc.init(null, trustAllCerts, new java.security.SecureRandom());
  
          HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  
      } catch (Exception e) {
              e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>Those changes worked very good, but I don´t want to Trust every server. I want to use my keystore file to validate the connection and use SSL in the right way.
  I read a lot on the internet and made a lot of tests, but I can´t understand what I have to do and how to do it.</p>
  
  <p>Can somebody help me?</p>
  
  <p>Thank you very much</p>
  
  <p>Sorry for my poor english</p>
  
  <p>-------------------------UPDATE 2011/08/24-------------------------------------------------</p>
  
  <p>Well, I'm still working on this. I made a new method to set the KeyStore, InputStream, etc</p>
  
  <p>The method looks like this:</p>
  
  <pre><code>private static void trustIFNetServer() {
  
      try {
          TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  
          KeyStore ks = KeyStore.getInstance("BKS");
  
          InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
  
          String keyPassword = "password"; 
  
          ks.load(in, keyPassword.toCharArray());
  
          in.close();
  
          tmf.init(ks);
  
          TrustManager[] tms = tmf.getTrustManagers();    
  
          SSLContext sc = SSLContext.getInstance("TLS");
  
      sc.init(null, tms, new java.security.SecureRandom());
  
      } catch (Exception e) {
      e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>First I had a lot of problems with the Key and the Certificate, but now it is working (I think so)</p>
  
  <p>My problem right now is a TimeOut Exception. I don´t know why it is generated. I'm think it's something with the data write, but I can't solve yet.</p>
  
  <p>Any Idea?</p>