static public void trustHttpsCertificates() throws Exception { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //Create a trust manager that does not validate certificate chains: TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { return; } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { return; } }//X509TrustManager };//TrustManager[] //Install the all-trusting trust manager: SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); //SSLSocketFactory sf = sc.getSocketFactory(); //System.out.println(sf.getClass()); //System.out.println(HttpsURLConnection.getDefaultSSLSocketFactory().getClass()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); //avoid "HTTPS hostname wrong: should be <myhostname>" exception: HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) { System.out.println("Warning: URL host '"+urlHostName+"' is different to SSLSession host '"+session.getPeerHost()+"'."); } return true; //also accept different hostname (e.g. domain name instead of IP address) } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); }//trustHttpsCertificates
All one can think and do in a short time is to think what one already knows and to do as one has always done!
javax.net.ssl.SSLException: untrusted server cert chain issue
When reading the content from a HTTPS connection, a javax.net.ssl.SSLException: untrusted server cert chain can be thrown for untrusted servers. To force reading from such untrusted servers, this method installs a 'all-trustung' trust manager that returns 'true' for all servers. Just call this method and install a dummy host name verifier to read data from any uncertified server.
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.