电容器 github 上有一个可行的解决方案https://github.com/ionic-team/capacitor/issues/3707#issuecomment-713360155
重要提示:这应该仅用于调试,如果您将此代码留在生产版本中,您的应用程序可能会被拒绝。该代码忽略 SSL 错误,因此不应出现在任何实时代码中。
对于Capacitor v3,我导入这些行:
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
然后在我的应用程序的 MainActivity.java 中添加对onStart()的覆盖
@Override
public void onStart() {
super.onStart();
if (BuildConfig.DEBUG) {
this.bridge.getWebView().setWebViewClient(new BridgeWebViewClient(this.bridge) {
@Override
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
handler.proceed();
}
});
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// Not implemented
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// Not implemented
}
}};
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } });
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
对于Capacitor v2,这可能有效 - 但如果不是,代码可以从 onStart() 移动到 onCreate(Bundle savedInstanceState) ,我在升级到 v3 之前看到它在工作。
我从 CLI 运行它
ionic capacitor run android -l --host=0.0.0.0 --consolelogs --external --ssl