4

当使用 Self singed certificate 与 REST API 建立 Https 连接时,我在 Android 9 中收到错误 javax.net.ssl.SSLPeerUnverifiedException: Hostname 196.1X.3X.X2 not verify。但它适用于 Android (Pie) 之前的 Android 版本。我把主机名是正确的。该怎么办 ?提前致谢。

我的代码如下。

public static String getResponse(String url) { 
    URL updateURL  ; 
   HttpsURLConnection  connection = null; 
    try { 
        HostnameVerifier hostnameVerifier = ( hostname, session ) ->{
            HostnameVerifier hv =
                    HttpsURLConnection.getDefaultHostnameVerifier();
            return hv.verify(Common.getHostnameSubject()+"", session )  ;
        };
        updateURL = new URL(url);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        InputStream caInput =  AppApplication.getAppContext().
                getAssets().open(Common.getCertificateAssetName());  
        Certificate ca; 
        ca = cf.generateCertificate(caInput);  
        caInput.close(); 
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType); 
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca); 
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore); 
        SSLContext context = SSLContext.getInstance("TLSv1.2"); 
        context.init(null, tmf.getTrustManagers(), null); 
        connection = (HttpsURLConnection) updateURL.openConnection(); 
        if( Common.isHostnameverficationManual() ) {
            connection.setHostnameVerifier(hostnameVerifier);
        }
        connection.setConnectTimeout(60000);
        connection.setSSLSocketFactory(context.getSocketFactory());
        int status = connection.getResponseCode();  
        InputStream is = new BufferedInputStream( connection.getInputStream() ); 
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder("");
        String line;
        String nl = System.getProperty("line.separator"); 
        while ((line = in.readLine()) != null) {
            sb.append(line).append(nl);
        } 
            result = sb.toString();
    } catch ( IOException | NoSuchAlgorithmException | KeyManagementException | CertificateException | KeyStoreException e ) { 
        if (connection != null) {
            connection.disconnect(); 
        }
    } 
    return result; 
} 
4

1 回答 1

5

请尝试此代码。

HttpsURLConnection.setDefaultHostnameVerifier((hostname, sslSession) -> {
    if(hostname.equals("196.1X.3X.X2")) return true;
    return false;
});

您应该确认 lambda 正在您的 android studio 环境中工作。

于 2019-01-04T14:45:40.083 回答