如何通过动态生成的链接在Webview中下载文件?

时间:2018-12-17 06:55:06

标签: android android-webview

我正在尝试通过动态生成的链接(如this)下载文件。它要求填写验证码并重定向到下载PDF文件的链接。

我正在使用webview.setDownloadListener,但不适用于我。这是代码:

public class MyDownloadListener implements DownloadListener {
private Context context;

MyDownloadListener(Context context) {
    this.context = context;
}

@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
    if (!hasStoragePermission())
        return;
    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 + "/NVSP/", URLUtil.guessFileName(url, contentDisposition, mimeType));
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    dm.enqueue(request);
    Toast.makeText(context, "Downloading File", Toast.LENGTH_LONG).show();
}

private boolean hasStoragePermission() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    return true;
}

}

webView.setDownloadListener(new MyDownloadListener(this));

0 个答案:

没有答案