Java SSL: how to disable hostname verification

前端 未结 5 1174
情深已故
情深已故 2020-11-29 01:54

Is there a way for the standard java SSL sockets to disable hostname verfication for ssl connections with a property? The only way I found until now, is to write a hostname

5条回答
  •  我在风中等你
    2020-11-29 02:11

    I also had the same problem while accessing RESTful web services. And I their with the below code to overcome the issue:

    public class Test {
        //Bypassing the SSL verification to execute our code successfully 
        static {
            disableSSLVerification();
        }
    
        public static void main(String[] args) {    
            //Access HTTPS URL and do something    
        }
        //Method used for bypassing SSL verification
        public static void disableSSLVerification() {
    
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
    
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
    
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
    
            } };
    
            SSLContext sc = null;
            try {
                sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };      
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);           
        }
    }
    

    It worked for me. try it!!

提交回复
热议问题