Home >Java >javaTutorial >How Can I Resolve 'SSL exception: Not trusted server certificate' Errors on Android?
Understanding HTTPS Connection Issues on Android
When attempting to establish an HTTPS connection on Android, you may encounter an "SSL exception: Not trusted server certificate" error. This error is typically encountered when using self-signed certificates or untrusted certificates.
Bypassing Certificate Verification
One method to resolve this issue is to disable certificate verification. This approach, however, compromises security by allowing connections to untrusted servers. The following code snippet from The Java Developers Almanac demonstrates how to trust all hosts and bypass certificate checking:
// Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); }
Conditional Handling Based on Protocol
Alternatively, you can conditionally handle the connection based on the protocol, as shown in the following code snippet:
if (url.getProtocol().toLowerCase().equals("https")) { trustAllHosts(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http = https; } else { http = (HttpURLConnection) url.openConnection(); }
By following these approaches, you can establish HTTPS connections and bypass certificate verification, but it's important to note that this compromises security and should be used with caution.
The above is the detailed content of How Can I Resolve 'SSL exception: Not trusted server certificate' Errors on Android?. For more information, please follow other related articles on the PHP Chinese website!