Android WebView 加载 https 网址会导致空白屏幕



WebView在http请求和https中工作正常,其中众所周知的受信任站点,如 https://www.online.citibank.co.in/但是我尝试使用第三方颁发的CA访问私人站点,它给出了空白屏幕。证书通过 SD 卡安装到手机,并列在受信任的证书列表下。

当我在将证书添加到 TrustManager 后使用 HttpsURLConnection 尝试相同的 URL 时,它工作正常(能够获取内容(。

以下是 WebView 和 HttpsURLConnection 的代码片段。

HttpsURLConnection:下面的代码工作正常,能够从URL获取内容(我无法共享URL,因为它无法从外部世界访问(

try
{
SSLContext context = null;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = getResources().openRawResource(R.raw.mi_net);
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
url = new URL(urlStr);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();  
con.setSSLSocketFactory(context.getSocketFactory());
con.setInstanceFollowRedirects(true);
con.setDoOutput(false);
con.setConnectTimeout(1000);
String responseMsg = con.getResponseMessage();
response = con.getResponseCode();
is = con.getInputStream();
}

WebView:不工作,在ReceivedSslError 上调用回调

{
WebSettings viewSettings = webView.getSettings();
viewSettings.setJavaScriptEnabled(true);
viewSettings.setAllowContentAccess(true);
viewSettings.setBuiltInZoomControls(false);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.loadUrl(sameURL);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(final WebView view, final String url, Bitmap favicon) {
Log.d("ann", "onPageStarted");
}
@Override
public void onPageFinished(final WebView view, String url) {
Log.d("ann", "inside onPageFinished");
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
if (!failingUrl.startsWith("mailto:")) {
webView.loadUrl("file:///android_asset/html/error.html");
}
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
super.onReceivedSslError(view, handler, error);
Log.d("ann","SSL error");
handler.proceed();
}
});}
}

请帮我提出建议。WebViewClient 异常为I/X509Util:无法验证证书链,错误:java.security.cert.CertPathValidator异常:找不到证书路径的信任锚。

对于 HttpsUrlConnection,您正在从文件创建证书并在运行时进行设置。

Web 视图必须使用系统中已有的任何内容。

这是一个类似的问题,并提出了解决方法:

签入 WebViewClient 的 onReceivedSslError(( 方法,如果证书是从特定的自签名 CA 签名的

您可以手动将自定义证书添加到您的安卓应用程序中!

文档链接

幸运的是,您可以通过以下方式教应用程序信任自定义 CA。 配置应用程序的网络安全配置,无需 需要修改应用程序内的代码。

有关如何设置的博客文章

最新更新