how to resolve jsoup error: unable to find valid certification path to requested target
Note: JSoup has deprecated and removed the validateTLSCertificates
method in version 1.12.1. See this answer for an alternative solution.
Prior to JSoup version 1.12.1, ignore TLS validation as follows:
Document doc = Jsoup.connect("URL").timeout(10000).validateTLSCertificates(false).get();
Since reading the page also takes a while, increase the timeout timeout(10000)
.
The selected answer will not work with latest releases of JSoup as validateTLSCertificates is deprecated and removed. I have created the following helper class :
public class SSLHelper {
static public Connection getConnection(String url){
return Jsoup.connect(url).sslSocketFactory(SSLHelper.socketFactory());
}
static private SSLSocketFactory socketFactory() {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory result = sslContext.getSocketFactory();
return result;
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException("Failed to create a SSL socket factory", e);
}
}
}
Then I simply call it as follows:
Document doc = SSLHelper.getConnection(url).userAgent(USER_AGENT).get();
(*) - https://dzone.com/articles/how-setup-custom - helpful in coming up with the solution