产品介绍
应用场景
产品优势
产品限制
WebSettings webSettings = mWebView.getSettings();// 使用默认的缓存策略,cache 没有过期就用 cachewebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);// 加载网页图片资源webSettings.setBlockNetworkImage(false);// 支持 JavaScript 脚本webSettings.setJavaScriptEnabled(true);// 支持缩放webSettings.setSupportZoom(true);mWebView.setWebViewClient(new WebViewClient() {// API 21及之后使用此方法@SuppressLint("NewApi")@Overridepublic WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {if (request != null && request.getUrl() != null && request.getMethod().equalsIgnoreCase("get")) {String scheme = request.getUrl().getScheme().trim();String url = request.getUrl().toString();Log.d(TAG, "url:" + url);// HTTPDNS 解析 css 文件的网络请求及图片请求if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))&& (url.contains(".css") || url.endsWith(".png") || url.endsWith(".jpg") || url .endsWith(".gif"))) {try {URL oldUrl = new URL(url);URLConnection connection = oldUrl.openConnection();// 获取 HTTPDNS 域名解析结果String ips = MSDKDnsResolver.getInstance().getAddrByName(oldUrl.getHost());String[] ipArr = ips.split(";");if (2 == ipArr.length && !"0".equals(ipArr[0])) { // 通过 HTTPDNS 获取 IP 成功,进行 URL 替换和 HOST 头设置String ip = ipArr[0];String newUrl = url.replaceFirst(oldUrl.getHost(), ip);connection = (HttpURLConnection) new URL(newUrl).openConnection(); // 设置 HTTP 请求头 Host 域名connection.setRequestProperty("Host", oldUrl.getHost());}Log.d(TAG, "contentType:" + connection.getContentType());return new WebResourceResponse("text/css", "UTF-8", connection.getInputStream());} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}return null;}// API 11至 API20使用此方法public WebResourceResponse shouldInterceptRequest(WebView view, String url) {if (!TextUtils.isEmpty(url) && Uri.parse(url).getScheme() != null) {String scheme = Uri.parse(url).getScheme().trim();Log.d(TAG, "url:" + url);// HTTPDNS 解析 css 文件的网络请求及图片请求if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))&& (url.contains(".css") || url.endsWith(".png") || url.endsWith(".jpg") || url.endsWith(".gif"))) {try {URL oldUrl = new URL(url);URLConnection connection = oldUrl.openConnection();// 获取 HTTPDNS 域名解析结果String ips = MSDKDnsResolver.getInstance().getAddrByName(oldUrl.getHost());String[] ipArr = ips.split(";");if (2 == ipArr.length && !"0".equals(ipArr[0])) { // 通过 HTTPDNS 获取 IP 成功,进行 URL 替换和 HOST 头设置String ip = ipArr[0];String newUrl = url.replaceFirst(oldUrl.getHost(), ip);connection = (HttpURLConnection) new URL(newUrl).openConnection(); // 设置 HTTP 请求头 Host 域名connection.setRequestProperty("Host", oldUrl.getHost());}Log.d(TAG, "contentType:" + connection.getContentType());return new WebResourceResponse("text/css", "UTF-8", connection.getInputStream());} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {}}}return null;}});// 加载web资源mWebView.loadUrl(targetUrl);
文档反馈