Android ICS:获取HttpsUrlConnection的服务器证书的问题

时间:2011-12-06 10:47:30

标签: android ssl android-4.0-ice-cream-sandwich

自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)       at 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);
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

Android: HTTPS (SSL) connection using HttpsURLConnection

httpclient ssl certificate on android

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();