2011-12-06 164 views
2

由於Android ICS我們有問題來驗證我們從HttpsUrlConnection獲得的證書。在早期版本的Android中,這很好。 這是我們正在嘗試做的:Android ICS:獲取HttpsUrlConnection服務器證書的問題

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

回答

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

的鏈接不能幫助我。我的問題只與Android 4有關。在2和3他們正在工作。 – zubke

+0

我認爲他們在ICS中做了一些修改。請看鏈接http://android-developers.blogspot.com/2011/09/androids-http-clients.html – Maneesh

+0

@zubke,請問您能指出什麼解決方案你以前? –

相關問題