Android 中加载本地Html 跨域问题,http协议允许加载

时间:2022-12-19 15:56:03

一、需求:

后台加载HTML的包时间太长,太卡,让把所有的HTML包放到前台;
使用的是file://协议,有些内容和样式加载不出来,H5那边说需要用http://协议来加载;

二、处理过程:

安卓最简单的加载本地HTML的方法是:webView.loadUrl("file:///android_asset/HtmlFileTT/index.html");
但是必须使用http 协议请求资源会有跨域问题,加载不了。

处理方式

 try {//本地HTML里面有跨域的请求 原生webview需要设置之后才能实现跨域请求
if (Build.VERSION.SDK_INT >= 16) {
Class<?> clazz = webView.getSettings().getClass();
Method method = clazz.getMethod(
"setAllowUniversalAccessFromFileURLs", boolean.class);
if (method != null) {
method.invoke(webView.getSettings(), true);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
webView.loadUrl("file:///android_asset/HtmlFileTT/index.html");
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
});