android连接https web service忽略证书的方法

如果直接连接https,都会出现报证书的错误,如果是正式用的话一定要添加证书,但是测试用的话,直接忽略掉证书,然后就可以继续连接上去。

解决方法如下:

在使用web service之前调用allowAllSSL()就行了。

public static void allowAllSSL() {  
javax.net.ssl.HttpsURLConnection  
        .setDefaultHostnameVerifier(new HostnameVerifier() {  
            public boolean verify(String hostname, SSLSession session) {  
                return true;  
            }  
        });  

javax.net.ssl.SSLContext context = null;  

if (trustManagers == null) {  
    trustManagers = new javax.net.ssl.TrustManager[] { new _FakeX509TrustManager() };  
}  

try {  
    context = javax.net.ssl.SSLContext.getInstance("TLS");  
    context.init(null, trustManagers, new SecureRandom());  
} catch (NoSuchAlgorithmException e) {  
    Log.e("allowAllSSL", e.toString());  
} catch (KeyManagementException e) {  
    Log.e("allowAllSSL", e.toString());  
}  
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context  
        .getSocketFactory());  

}`