javahttpssslhandshakeexception

Using jsoup to connect to untrusted certificate


I am having an issue with my java application. I use JSOUP to connect to a website that used to be http and is now moved to https. Now when I run the application I get the following error, is anyone able to help with this at all?

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 32 more
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
    at sun.security.ssl.Alerts.getSSLException(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)

Solution

  • If you trust the site you can ignore http errors by setting it to true:

    Document doc = Jsoup.connect("your_url").ignoreHttpErrors(true).get();
    

    and to ignore TSL validation, set validateTLSCertificates(false):

    Document doc = Jsoup.connect("your_url").validateTLSCertificates(false).get();
    

    EDIT

    This answer is outdated as JSoup has deprecated and removed the validateTLSCertificates method in version 1.12.1

    (https://jsoup.org/news/release-1.12.1).

    If you trust the questionable site and want to ignore TLS-validiation look at this answer how-to-resolve-jsoup-error-unable-to-find-valid-certification-path