Search code examples
javahttpshttp-putsslhandshakeexception

Java HttpsURLConnection SSLHandshakeException


I am attempting to make a HTTPS connection to a website using HttpsURLConnection, and then perform a PUT request. When I try to create the OutputStreamWriter from HttpsURLConnection.getOutputStream(), the following exception is thrown:

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

The page has just gotten its certificate (issued by StartCom) - do I need to manually do something to make Java recognise the certificate is present now? I can connect to other pages of the same website with no difficulty, but they have a different certificate.


Solution

  • You can import the root certificate of StartCom yia the tool keytool (from JDK) into a Java Key Store (JKS) and then set the key store as "trusted store".

    See section "Exporting and Importing Certificates" on:

    http://java.sun.com/developer/technicalArticles/Security/secureinternet2/

    Commands mentioned in that article:

    Import certifificate to trustedcerts.jks:

    keytool -import -keystore trustedcerts.jks -alias qusay -file server.crt
    

    Start Java using custom tuststore:

    java -Djavax.net.ssl.trustStore=trustedcerts.jks com.example.MyClass
    

    Alternatively you can set the truststore at runtime:

    System.setProperty("javax.net.ssl.trustStore","./trustedcerts.jks");