I am trying to connect to an https server from my program, so I've created a certificate client.cer where I put my server's DNS name as CN value. In my application I tried to import the certificate:
and of course it didn't work, well the certificate loaded but I got javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target when I tried to post to the server.
I think perhaps you are a little confused about the terminology. From the viewpoint of the client, you want to authenticate the server. To do so, you must configure the client's truststore so that it contains the CA root certificate that signed the server's certificate. Sometimes, and I'm guessing your application is one of these, the server certificate hierarchy just contains a single self-signed certificate. In this case, this certificate is functionally the CA root certificate. So this certificate must be preloaded in to the client's truststore. It only makes sense to do this prior to attempting a connection. There are many ways to configure the client's truststore; see http://java.sun.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CustomizingStores