I have set up a VPS hosting two websites with Apache. Both have a (valid) SSL configuration with a StartSSL certificate, and I have no problem accessing them from a desktop or mobile browser.
I am trying to access an API that one of the websites runs using SSL, but I'm having problems. I was first using Apache HttpClient (deprecated), but it looks like it can't choose the proper certificate on the server because it doesn't support Server Name Indication and that the workaround is using HttpsURLConnection.
So I currently have this code, shamelessly copied from the Internet:
String url = "https://mywebsite.ext/api/xxx";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
String urlParameters = "blah=foo&bar=xx";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
// ...
And what I get is:
Exception in thread "main" 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
(Which of course I don't get if I try to access for instance https://google.com)
After googling, I found that the issue seems to be that the root certificate of StartSSL is not recognized by the JVM (desktop) / android. I don't want to import it manually because the finality of this code is to run inside an Android application. I don't want either to loose all the interest of SSL by allowing any certificate, as I have seen in many answers.
Any insights?
Thank you