Android HttpsURLConnection仅在Android 4.4.2 nexus设备上引发非法状态异常
我有下面的代码可以在很多Android设备上使用(摩托罗拉Xoom(4.0.4,三星Galaxy S3(4.2.2),三星Galaxy tab 3(4.3)),但它在nexus 7和nexus 4上都不起作用(4.4.2),所以nexus设备问题或是4.4.2 Android版本Android HttpsURLConnection仅在Android 4.4.2 nexus设备上引发非法状态异常,android,https,connection,Android,Https,Connection,我有下面的代码可以在很多Android设备上使用(摩托罗拉Xoom(4.0.4,三星Galaxy S3(4.2.2),三星Galaxy tab 3(4.3)),但它在nexus 7和nexus 4上都不起作用(4.4.2),所以nexus设备问题或是4.4.2 Android版本 httpsURLConnection = (HttpsURLConnection)url.openConnection(); if(socketFactory!=null){ httpsURLConnecti
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上工作。我需要证书对它进行一些检查,我能做什么?缺少什么吗
非常感谢我也有同样的问题 我的代码在三星S3上运行,但在三星S4上出现异常“java.lang.IllegalStateException:尚未建立连接”时失败 要解决此问题,请在从连接读取一些数据后调用getServerCertificates() 在调用getServerCertificates()之前,先调用getInputStream(),然后再通过连接执行一些i/o 请参见下面的示例:
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;
}