2

自 Android ICS 以来,我们在验证我们从HttpsUrlConnection. 在早期版本的 android 中,这运行良好。这就是我们正在尝试做的事情:

BrowserCompatHostnameVerifier hostNameVerifier = new BrowserCompatHostnameVerifier();
HttpsURLConnection.setDefaultHostnameVerifier(hostNameVerifier);
URL url = new URL(serverUrl);
this.urlConnection = (HttpsURLConnection) url.openConnection();
this.urlConnection.connect();
hostNameVerifier.verify(urlConnection.getURL().getHost(),
(X509Certificate) urlConnection.getServerCertificates()[0]);

抛出的异常是:

java.lang.IllegalStateException 在 libcore.net.http.HttpEngine.getCacheResponse(HttpEngine.java:412) 在 libcore.net.http.HttpsURLConnectionImpl$HttpUrlConnectionDelegate.getCacheResponse(HttpsURLConnectionImpl.java:390) 在 libcore.net.http.HttpsURLConnectionImpl。 getServerCertificates(HttpsURLConnectionImpl.java:87)

有人知道可能出了什么问题以及为什么它只在 ICS 之后持续存在吗?

谢谢!

----- 更新 -------- 现在我像这样制作了自己的 HostnameVerifier。我避免像这样的 getServerCertificates() 方法,它正在工作:

    public class MyHostNameVerifier implements HostnameVerifier {

    private String expectedHost;

    public MyHostNameVerifier(String expectedHost) {
        this.expectedHost = expectedHost;
    }

    @Override
    public boolean verify(String hostname, SSLSession session) {
        return expectedHost.equals(hostname);
    }
}
4

1 回答 1

0

尝试查看以下与您的问题相关的链接。

http://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html

Android:使用 HttpsURLConnection 的 HTTPS (SSL) 连接

android上的httpclient ssl证书

KeyStore keyStore = ...;
 TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
 tmf.init(keyStore);
 SSLContext context = SSLContext.getInstance("TLS");
 context.init(null, tmf.getTrustManagers(), null);
 URL url = new URL("https://www.example.com/");
 HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
 urlConnection.setSSLSocketFactory(context.getSocketFactory());
 InputStream in = urlConnection.getInputStream();
于 2011-12-06T10:56:34.070 回答