gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:21:32 24 4
gpt4 key购买 nike

我有以下代码适用于许多 Android 设备(Motorola Xoom(4.0.4、Samsung Galaxy S3(4.2.2)、Samsung galaxy tab 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: Connection has not yet been established :

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

我不明白为什么以及为什么它适用于其他设备而不是 nexus 7/nexus 4。我需要证书来对其进行一些检查,我该怎么办?是不是少了什么?

非常感谢

最佳答案

我也有同样的问题。

我的代码在三星 S3 上运行,但在三星 S4 上出现异常“java.lang.IllegalStateException:尚未建立连接”失败。

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

在调用 getServerCertificates() 之前先调用 getInputStream() 以通过连接执行一些输入/输出。

请看下面的例子:

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;
}

关于Android HttpsURLConnection 仅在 Android 4.4.2 nexus 设备上抛出 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22767615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com