Android HttpsURLConnection仅在Android 4.4.2 nexus设备上抛出IllegalStateException

时间:2014-03-31 16:55:18

标签: android https connection

我有以下代码适用于许多Android设备(摩托罗拉Xoom(4.0.4,三星Galaxy S3(4.2.2),三星Galaxy标签3(4.3)),但它对nexus 7无效,也不适用于nexus 4两者(4.4.2)所以nexus设备问题或4.4.2 android版本。

httpsURLConnection = (HttpsURLConnection)url.openConnection();

if(socketFactory!=null){
    httpsURLConnection.setSSLSocketFactory(socketFactory);
} else {
   log.w("tryConnecting : socket factory is null");
}
httpsURLConnection.setHostnameVerifier(new MzHostNameVerifier());

httpsURLConnection.connect();
int responseCode = httpsURLConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
Certificate[] certificate = httpsURLConnection.getServerCertificates();
httpsURLConnection.disconnect();
return certificate;
} else {
log.e("Connection error, code : "+responseCode);
return null;
}

我得到异常 java.lang.IllegalStateException:尚未建立连接

   **Certificate[] certificate = httpsURLConnection.getServerCertificates();**

我不明白为什么以及它为什么在其他设备上运行而不是nexus 7 / nexus 4.我需要证书对它进行一些检查,我该怎么办?有什么遗失的吗?

非常感谢

1 个答案:

答案 0 :(得分:2)

我也有同样的问题。

我的代码在三星S3上运行,但由于异常而失败" java.lang.IllegalStateException:尚未建立连接"在三星S4上。

要解决问题,请在从连接中读取一些数据后调用getServerCertificates()。

在调用getServerCertificates()之前,先调用getInputStream(),然后再通过连接执行一些i / o。

请参阅以下示例:

enter image description here

private boolean ValidateHTTPSCertificate()
    {
        boolean result = false;
        String serverCertPublicSerial = "abcdefghijklmnopqrstuvwxyz";

        try
        {
            URL url = new URL( "https://your-url-goes-here" );
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

            if(con!=null){

                try {
                    con.connect();

                    int respCode =  con.getResponseCode();
                    String pageResult = convertInputStreamToString(con.getInputStream());

                    Certificate[] certs = con.getServerCertificates();
                    for(Certificate cert : certs){

                        X509Certificate x509cert = (X509Certificate)cert;

                        BigInteger serialNum = x509cert.getSerialNumber();

                        String name = x509cert.getIssuerDN().getName();
                        String publicKeySerial = serialNum.toString(16);

                        if (publicKeySerial.toLowerCase().equals(serverCertPublicSerial.toLowerCase()) == true )
                        {
                            result = true;
                            break;
                        }
                    }
                    //con.disconnect();
                } catch (SSLPeerUnverifiedException e) {
                    e.printStackTrace();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        catch (Exception ex)
        {
            String  msg = ex.getMessage();
        }

        return result;
    }