下面列出了怎么用android.webkit.WebResourceResponse的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
/*
ByteArrayInputStream EMPTY = new ByteArrayInputStream("".getBytes());
if (mAdBlock.isAd(request.getUrl().getHost())) {
return new WebResourceResponse("text/plain", "utf-8", EMPTY);
}
if(request.getUrl().getHost().indexOf("127.0.0.1")>=0){
//ToastUtil.showMessage("this site is insecure");
return new WebResourceResponse("text/plain", "utf-8", EMPTY);
}
*/
return super.shouldInterceptRequest(view, request);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private WebResourceResponse handleImageRequest(final WebView aWebView, final WebResourceRequest request, String strMimeType)
{
KCWebView webView = (KCWebView) aWebView;
if (mImageDownloader == null)
mImageDownloader = new KCWebImageDownloader(webView.getContext(), webView.getWebPath());
if (mWebImageHandler==null)
mWebImageHandler = new KCWebImageHandler(mWebImageListener);
KCWebImage webImage = mImageDownloader.downloadImageFile(request.getUrl().toString(), mWebImageHandler.add(request.getUrl().toString()));
InputStream stream = webImage.getInputStream();
if (stream == null)
{
Log.e("image", "current stream is null,download image from net");
return null;
}
return new WebResourceResponse(strMimeType, "utf-8", stream);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
String url = request.getUrl().toString();
if (HostManager.getInstance().shouldIntercept(url)) {
return new WebResourceResponse(null, null, null);
} else {
if (!isUsePlayer) {
DetectorManager.getInstance().addTask(new Video(url, url));
}
if (needCache) {
return WebViewCacheInterceptorInst.getInstance().interceptRequest(request);
} else {
return super.shouldInterceptRequest(view, request);
}
}
}
if (needCache) {
return WebViewCacheInterceptorInst.getInstance().interceptRequest(request);
} else {
return super.shouldInterceptRequest(view, request);
}
}
@Override
public WebResourceResponse getResource(WebResourceRequest webResourceRequest, int cacheMode, String userAgent) {
if (mFastCacheMode == FastCacheMode.DEFAULT) {
throw new IllegalStateException("an error occurred.");
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
String url = webResourceRequest.getUrl().toString();
String extension = MimeTypeMapUtils.getFileExtensionFromUrl(url);
String mimeType = MimeTypeMapUtils.getMimeTypeFromExtension(extension);
CacheRequest cacheRequest = new CacheRequest();
cacheRequest.setUrl(url);
cacheRequest.setMime(mimeType);
cacheRequest.setForceMode(mFastCacheMode == FastCacheMode.FORCE);
cacheRequest.setUserAgent(userAgent);
cacheRequest.setWebViewCacheMode(cacheMode);
Map<String, String> headers = webResourceRequest.getRequestHeaders();
cacheRequest.setHeaders(headers);
return getOfflineServer().get(cacheRequest);
}
throw new IllegalStateException("an error occurred.");
}
/**
* Attempt to retrieve the WebResourceResponse associated with the given <code>request</code>.
* This method should be invoked from within
* {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView,
* android.webkit.WebResourceRequest)}.
*
* @param request the request to process.
* @return a response if the request URL had a matching handler, null if no handler was found.
*/
public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
Uri loadingUrl = request.getUrl();
PathHandler handler;
synchronized (uriMatcher) {
handler = (PathHandler) uriMatcher.match(request.getUrl());
}
if (handler == null) {
return null;
}
if (isLocalFile(loadingUrl) || loadingUrl.toString().startsWith(bridge.getLocalUrl())) {
Log.d(LogUtils.getCoreTag(), "Handling local request: " + request.getUrl().toString());
return handleLocalRequest(request, handler);
} else {
return handleProxyRequest(request, handler);
}
}
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onPageLoadError(WebView view, WebResourceRequest request,
WebResourceResponse errorResponse,
boolean isMainRequestFailure) {
if (isMainRequestFailure) {
errorNotification.showError(getContext(),
new HttpStatusException(Response.error(errorResponse.getStatusCode(),
ResponseBody.create(MediaType.parse(errorResponse.getMimeType()),
errorResponse.getReasonPhrase()))),
R.string.lbl_reload, new View.OnClickListener() {
@Override
public void onClick(View v) {
onRefresh();
}
});
clearWebView();
}
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the white-list.
if ((url.startsWith("http:") || url.startsWith("https:")) && !Config.isUrlWhiteListed(url)) {
LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
CordovaResourceApi resourceApi = appView.getResourceApi();
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri)) {
OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e("IceCreamCordovaWebViewClient", "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
public List<Caption> getCaptions(String youtubeId) {
Log.d(LOG_TAG, "getCaptions: " + youtubeId);
List<Caption> result = null;
Dao<Caption, Integer> captionDao = null;
try {
captionDao = dataService.getHelper().getDao(Caption.class);
QueryBuilder<Caption, Integer> q = captionDao.queryBuilder();
q.where().eq("youtube_id", youtubeId);
q.orderBy("sub_order", true);
// TODO : Avoid inserting duplicates in the first place, and do a migration to clean up.
q.groupBy("sub_order");
result = q.query();
} catch (SQLException e) {
e.printStackTrace();
}
if (result != null && result.size() > 0) {
Log.d(LOG_TAG, " already cached; returning");
return result;
}
// If we do not already have the captions, try fetching them.
// Clients will call this in a background thread, so we can take our time.
WebResourceResponse response = fetchRawCaptionResponse(youtubeId);
result = parseAPIResponse(response);
result = pruneEmptyCaptions(result);
result = persist(result, youtubeId);
return result;
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the white-list.
if ((url.startsWith("http:") || url.startsWith("https:")) && !Config.isUrlWhiteListed(url)) {
LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
CordovaResourceApi resourceApi = appView.getResourceApi();
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e("IceCreamCordovaWebViewClient", "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
private WebResourceResponse getTweenJs() {
try {
AssetManager as = context.getAssets();
InputStream is = as.open("tweenjs-0.6.2.min.js");
return new WebResourceResponse("application/x-javascript", "utf-8", is);
} catch (IOException e) {
return null;
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse interceptRequest( WebResourceRequest request) {
if (mInterceptor==null){
return null;
}
return mInterceptor.interceptRequest(request);
}
@Override
@SuppressWarnings("deprecation")
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the whitelist and lock out access to the WebView directory
// Changing this will cause problems for your application
if (!parentEngine.pluginManager.shouldAllowRequest(url)) {
LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
CordovaResourceApi resourceApi = parentEngine.resourceApi;
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the whitelist and lock out access to the WebView directory
// Changing this will cause problems for your application
if (!parentEngine.pluginManager.shouldAllowRequest(url)) {
LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
CordovaResourceApi resourceApi = parentEngine.resourceApi;
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
String url = null != webResourceRequest.getUrl() ? webResourceRequest.getUrl().toString() : null;
if (!TextUtils.isEmpty(url) && url.startsWith(LOCAL_FILE_SCHEMA)) {
return getLocalResource(url);
}
if (null != _webViewDelegate && null != _webViewDelegate.get()) {
return _webViewDelegate.get().shouldInterceptRequest(webView, webResourceRequest);
}
return super.shouldInterceptRequest(webView, webResourceRequest);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
url = url.toLowerCase();
if (!hasAdUrl(url)) {
//正常加载
return super.shouldInterceptRequest(view, url);
} else {
//含有广告资源屏蔽请求
return new WebResourceResponse(null, null, null);
}
}
public void onReceivedHttpError(WebView view, WebResourceRequest request,
WebResourceResponse errorResponse) {
Tracker.prolongMetric();
if (com_rakuten_tech_mobile_perf_page_trackingId != 0) {
Tracker.endUrl(com_rakuten_tech_mobile_perf_page_trackingId, errorResponse.getStatusCode(),
null, 0);
com_rakuten_tech_mobile_perf_page_trackingId = 0;
}
super.onReceivedHttpError(view, request, errorResponse);
}
@SuppressLint("NewApi")
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
String errRespStr = "";
if (errorResponse != null) {
if (Util.isCompateApi(21)) {
errRespStr += "status code =" + errorResponse.getStatusCode() + " | reason : " + errorResponse.getReasonPhrase();
}
}
e(null, "--> onReceivedHttpError() request url = " + request.getUrl() + " errRespStr = " + errRespStr);
}
@Override
@SuppressWarnings("deprecation")
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the whitelist and lock out access to the WebView directory
// Changing this will cause problems for your application
if (!parentEngine.pluginManager.shouldAllowRequest(url)) {
LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
CordovaResourceApi resourceApi = parentEngine.resourceApi;
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains("?__cf_chl_captcha_tk__")) {
runOnUiThread(() -> webView.evaluateJavascript("javascript:getPostData()", value -> {
String postData = value.replace("\"", "");
Logger.t(TAG).d(postData);
String[] data = postData.split(",");
Logger.t(TAG).d(data);
if (data.length >= 4) {
doPost(data[0], data[1], data[2], data[3]);
} else {
showMessage("无法获取POST数据,请刷新重试", TastyToast.ERROR);
btnRefresh.setText("刷新重试");
}
}));
synchronized (lock) {
try {
//等待验证结果
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return new WebResourceResponse("", "", null);
}
Log.d(TAG, url);
return super.shouldInterceptRequest(view, request);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
Uri uri = Uri.parse(url);
String host = uri.getHost();
if (host != null && host.equals("cdnjs.cloudflare.com")) {
String path = uri.getPath().substring("/ajax/libs".length());
try {
return loadFileFromAssets(url, "cdnjs" + path);
} catch (IOException e) {
return null;
}
}
return null;
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the white-list.
if ((url.startsWith("http:") || url.startsWith("https:")) && !Config.isUrlWhiteListed(url)) {
LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
CordovaResourceApi resourceApi = appView.getResourceApi();
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri)) {
OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e("IceCreamCordovaWebViewClient", "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
@TargetApi(21)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(request.getUrl().toString());
String mimeType = MimeUtils.guessMimeTypeFromExtension(fileExtension);
return new WebResourceResponse(mimeType, "UTF-8", new ClosedInputStream());
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
if (mDelegate != null) {
mDelegate.onReceivedHttpError(view, request, errorResponse);
return;
}
super.onReceivedHttpError(view, request, errorResponse);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
// don't intercept request below android 5.0
// bc we can not get request method, request body and request headers
// delegate intercept first
return mDelegate != null ? mDelegate.shouldInterceptRequest(view, url) : null;
}
@Override
@SuppressWarnings("deprecation")
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the whitelist and lock out access to the WebView directory
// Changing this will cause problems for your application
if (!parentEngine.pluginManager.shouldAllowRequest(url)) {
LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
CordovaResourceApi resourceApi = parentEngine.resourceApi;
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private WebResourceResponse loadFromWebViewCache(WebResourceRequest request) {
String scheme = request.getUrl().getScheme().trim();
String method = request.getMethod().trim();
if ((TextUtils.equals(SCHEME_HTTP, scheme)
|| TextUtils.equals(SCHEME_HTTPS, scheme))
&& method.equalsIgnoreCase(METHOD_GET)) {
return mWebViewCache.getResource(request, mWebViewCacheMode, mUserAgent);
}
return null;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the whitelist and lock out access to the WebView directory
// Changing this will cause problems for your application
if (!parentEngine.pluginManager.shouldAllowRequest(url)) {
LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
CordovaResourceApi resourceApi = parentEngine.resourceApi;
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
boolean ad;
url = IntentActivity.getRedirectUrl(url);
if (!loadedUrls.containsKey(url)) {
ad = AdBlocker.isAd(url);
loadedUrls.put(url, ad);
} else {
ad = loadedUrls.get(url);
}
return ad ? AdBlocker.createEmptyResource() :
super.shouldInterceptRequest(view, url);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
// Check the against the whitelist and lock out access to the WebView directory
// Changing this will cause problems for your application
if (!parentEngine.pluginManager.shouldAllowRequest(url)) {
LOG.w(TAG, "URL blocked by whitelist: " + url);
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
CordovaResourceApi resourceApi = parentEngine.resourceApi;
Uri origUri = Uri.parse(url);
// Allow plugins to intercept WebView requests.
Uri remappedUri = resourceApi.remapUri(origUri);
if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {
CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri, true);
return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
}
// If we don't need to special-case the request, let the browser load it.
return null;
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);
}
// Results in a 404.
return new WebResourceResponse("text/plain", "UTF-8", null);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains("?__cf_chl_captcha_tk__")) {
runOnUiThread(() -> webView.evaluateJavascript("javascript:getPostData()", value -> {
String postData = value.replace("\"", "");
Logger.t(TAG).d(postData);
String[] data = postData.split(",");
Logger.t(TAG).d(data);
if (data.length >= 4) {
doPost(data[0], data[1], data[2], data[3]);
} else {
showMessage("无法获取POST数据,请刷新重试", TastyToast.ERROR);
btnRefresh.setText("刷新重试");
}
}));
synchronized (lock) {
try {
//等待验证结果
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return new WebResourceResponse("", "", null);
}
Log.d(TAG, url);
return super.shouldInterceptRequest(view, request);
}