Android WebView-不要从WebView下载文件

时间:2018-07-04 16:21:43

标签: android

我正在使用此Downloadlistener

mWebView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDescription,
                                    String mimetype, long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(
                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            String fileName = URLUtil.guessFileName(url,contentDescription,mimetype);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
            DownloadManager dManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dManager.enqueue(request);
        }
    });

但是不能在我需要的网站上工作。如果我使用例如这个网址

https://www.sendspace.com/....

文件已正常下载。

但是,如果我使用此网址

http://m.slovakrail.sk

然后我购买了票,并在最后一个站点上单击了下载按钮,但是下载不起作用。 网站的按钮代码为

<input type="submit" name="j_idt91:j_idt93:0:j_idt94" value="Stiahnuť cestovný doklad" class="btn" />

谢谢您的答复。

1 个答案:

答案 0 :(得分:0)

我认为下载表单使用POST。我发现这样做的唯一方法是使用webView.loadUrl("javascript:...")注入JavaScript代码,该代码从表单中提取所有需要的信息。然后手动执行POST请求,以下载文件。 (例如,使用OkHttp。)

要让DownloadManager知道下载的文件,可以使用downloadManager.addCompletedDownload(...)方法。


示例代码(科特琳)

webView.loadUrl("""
    javascript:(function () {
        let form = document.querySelector("#form-id");
        let inputs = [...form.querySelectorAll("input[type='hidden']")];
        form.querySelector("button.pdfLink[type='submit']").addEventListener(
            'click',
            (e) => {
                e.stopPropagation();
                e.preventDefault();
                App.download(JSON.stringify({
                    method: form.method,
                    url: form.action,
                    fields: inputs.map(f => ({key: f.name, value: f.value}))
                }));
            },
            false);
    })()
    """.trimIndent())

您还需要将JS接口添加到WebView

webView.addJavascriptInterface(adapter, "App")

WebView JS适配器看起来可能与此类似:

class WebViewJsAdapter {
    @JavascriptInterface
    fun download(formData: String) {
        val data = JSONObject(formData)
        // 1. download the file
        ...
        // 2. add the downloaded file to the DownloadManager
        //    using `downloadManager.addCompletedDownload(...)`
        ...
    }
}