android – 如何让离子库信任自签名证书

我正在尝试连接到必须使用自签名证书的REST服务(它是Unify PBXs Web服务接口).系统将在软件更新时重新生成它的证书,除非您将证书加载到系统中,否则将始终存在自签名证书.
当尝试连接离子时,连接因为自签名证书而关闭(据谷歌带我…).我需要添加到我的实现中以使io接受此证书?
我使用离子如下.

Ion.with(context)
     .load(...)
     .asString()
     .setCallback(new FutureCallback<String>() {
           @Override
           public void onCompleted(Exception e, String result) {
           }
      });

解决方法:

您可以指定自定义SSL上下文和信任管理器以使用自签名证书.

以下是单元测试的示例:

public void testKeys() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    ks.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    kmf.init(ks, "storepass".toCharArray());


    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
    ts.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    tmf.init(ts);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    AsyncHttpServer httpServer = new AsyncHttpServer();
    httpServer.listenSecure(8888, sslContext);
    httpServer.get("/", new HttpServerRequestCallback() {
        @Override
        public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
            response.send("hello");
        }
    });

    Thread.sleep(1000);

    AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(sslContext);
    AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setTrustManagers(tmf.getTrustManagers());
    AsyncHttpClient.getDefaultInstance().executeString(new AsyncHttpGet("https://localhost:8888/"), null).get();
}

您需要访问ion的底层http客户端实例,如下所示:

Ion.getDefault(getContext()).getHttpClient().getSSLSocketMiddleware().setTrustManagers(...);
Ion.getDefault(getContext()).getHttpClient().getSSLSocketMiddleware().setSSLContext(...);

关键是一个bks钥匙店,充气城堡.

上一篇:English Grammar - Subject Clause


下一篇:Ionic4.x 中的 UI 组件(UI Components) 侧边栏ion-menu组件以及底部tabs结合 侧边栏 ion-menu