title: How to get server certificate in java
body: <p>I am working on a client program(in android) which needs to communicate with a jboss server via SSL. Currently I have followed the instructions from <a href="http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html" rel="nofollow">http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html</a> to get the self-signed certificate and connect to the server. I am wondering if this can be done from java since whenever server certificate changes , I have to manually get the certificate and compile it into the code itself. I have also noticed that google chrome in android can do this. Any idea how to achieve this.
  Thanks.</p>
  
  <p>I am using this test code to get server certificate without success. </p>
  
  <pre><code>public class TestCert {
  public static void main(String args[]) throws Exception {
      SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
      SSLSocket socket = (SSLSocket) factory.createSocket(&lt;ip&gt;, &lt;port&gt;);
      socket.startHandshake();
      SSLSession session = socket.getSession();
      java.security.cert.Certificate[] servercerts = session.getPeerCertificates();
  
      List mylist = new ArrayList();
      for (int i = 0; i &lt; servercerts.length; i++) {
          mylist.add(servercerts[i]);
      }
  
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      CertPath cp = cf.generateCertPath(mylist);
  
      FileOutputStream f = new FileOutputStream("/tmp/CertPath.dat");
      ObjectOutputStream b = new ObjectOutputStream(f);
      b.writeObject(cp);
  }
  }
  </code></pre>