在WebView的WebViewClient中覆盖shouldInterceptRequest方法,以在请求URL时设置正确的缓存模式。以下是示例代码:
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
WebResourceRequest request = new WebResourceRequest(url, true);
String reqUrl = request.getUrl().toString();
boolean isForMainFrame = request.isForMainFrame();
boolean isRedirect = request.isRedirect();
boolean hasGesture = request.hasGesture();
String method = request.getMethod();
//设置WebView的缓存模式
if (!TextUtils.isEmpty(reqUrl)) {
CacheControl cacheControl = new CacheControl.Builder()
.noCache()
.build();
Request newRequest = new Request.Builder()
.cacheControl(cacheControl)
.url(reqUrl)
.build();
return super.shouldInterceptRequest(view, newRequest);
} else {
return super.shouldInterceptRequest(view, url);
}
}