0

我正在使用 HttpsURLConnection 执行 HTTPS 请求。

我尝试联系的服务器具有自签名证书,因此这在逻辑上会导致请求失败。

但是,异常不会向我的程序发出失败信号。它只是失败了,我可以在 logcat 中看到原因。

03-22 17:54:35.203: W/System.err(21147): javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
03-22 17:54:35.203: W/System.err(21147):    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:381)

这是我用于请求的代码:

HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.connect();

理想情况下,我希望我的程序像浏览器一样做出反应:弹出一个对话框,指示证书不受信任,并可能将其添加到某个密钥库并重试请求。

但是由于我无法弄清楚获取异常的方法,所以我真的不知道该怎么做。

有什么线索吗?

4

2 回答 2

2

While huge is correct that you need to implement a custom TrustManager, you should absolutely not just blindly accept all SSL certificates.

Nikolay Elenikov has an excellent blog post describes how to set up a custom TrustManager to validate such certificates

于 2013-03-22T18:42:08.647 回答
-4

你可以这样做:

SSLContext sc = SSLContext.getInstance("TLS");
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        return;
}
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        return;
    }
} };
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpURLConnection = connection = endPoint.openConnection();
于 2013-03-22T17:30:39.013 回答