Home >Java >javaTutorial >How Can I Handle Unverified HTTPS Connections in Android?
Unverified Https Connection in Android
When performing HTTP(S) requests, if you encounter an "SSL exception Not trusted server certificate" error while using HTTPS, you may need to handle server certificate verification explicitly.
Solution:
To bypass certificate verification and trust all servers, you can implement the following code:
// Ignore hostname verification HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Trust all certificates TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } // Open the connection, setting hostname verification to false and using the custom trust manager HttpURLConnection http = null; if (url.getProtocol().toLowerCase().equals("https")) { HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http = https; } else { http = (HttpURLConnection) url.openConnection(); }
With this code, SSL certificate validation will be skipped for both normal HTTP and HTTPS connections.
The above is the detailed content of How Can I Handle Unverified HTTPS Connections in Android?. For more information, please follow other related articles on the PHP Chinese website!