在Android Studio的WebView中下载文件时,如果使用了“admin-ajax.php”扩展名的文件,可能会导致下载无法正常进行。这是因为默认情况下,Android Studio WebView不允许在WebView中打开或下载文件,除非文件的MIME类型与WebView的允许类型相匹配。
要解决这个问题,我们需要在应用程序中添加以下代码:
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
//------------------------COOKIE!!------------------------
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
//------------------------COOKIE!!------------------------
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition,
mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
URLUtil.guessFileName(url, contentDisposition,
mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}
});
这段代码将允许在WebView中下载文件,并设置了DownloadManager用于管理下载进程。
在下载过程中会实例化一个DownloadManager.Request对象,其中包含了文件下载的各种参数。重要的是,我们需要在请求头中添加cookie以便进行授权。
此外,我们还需要添加以下权限,以便下载管理器能够访问设备存储:
完成上述设置后,WebView