从 Android 的 WebView 中的 Blob Url 下载 PDF 文件

Rik*_*kin 5 java android webview kotlin

场景:

  • 我有一个生成 pdf 文件的 RestFul API
  • 我使用此 API 在 Web 应用程序中下载 pdf 文件并且效果很好
  • 现在我想在 Android 应用程序的 Webview 中打开此 Web 应用程序以下载相同的文件

问题是,我正在做类似的事情来管理 Webview 下载:

webview.settings.javaScriptEnabled = true
webview.settings.domStorageEnabled = true

webview.setDownloadListener { url, userAgent, contentDisposition, mimeType, _ ->
    val subpath = "/download" + "/" + "test" + ".pdf"
    val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    val request = DownloadManager.Request(Uri.parse(formatUri(url)))
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
    request.setAllowedOverRoaming(false)
    request.setVisibleInDownloadsUi(true)
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subpath)
    downloadManager.enqueue(request)            
}
Run Code Online (Sandbox Code Playgroud)

但是,当然,这将不起作用,因为返回的url不是“正常”的 Uri,例如:

https://test.com/your-pdf-file.pdf

相反,它更像是这样:

斑点:https : //test.com/d335cd66-b3f2-4fd5-b16f-asbca22dfc38

Web 浏览器可以使用这种 url,但 webview 不能。

如何让 Android webview 将文件下载到设备?