[英]How to use the MuPDF library to open pdf files when a pdf file is opened from webview
[英]How to open a PDF from WebView when PDF is secured by a cookie?
我正在尝试从我的 WebView 下载并打开一个 PDF 文件。 我尝试从 WebView 检索 cookie,并在 DownloadManager.Request 上设置 cookie。 当我的 BroadCastReceiver 被触发时,下载状态表明它已失败。
this.webView?.apply {
settings.domStorageEnabled = true
settings.javaScriptEnabled = true
setDownloadListener { url, _, _, mimetype, _ ->
Log.w("downloading file", url)
val downloadUri = Uri.parse(url)
val downloadRequest = DownloadManager.Request(downloadUri).apply {
setTitle("Title")
setDescription("Downloading file")
Log.w("path", "${downloadUri.lastPathSegment}")
setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, downloadUri.lastPathSegment)
val cookie = getCookie("https://www.example.com", "example_cookie_name")
Log.w("cookie", "${cookie}")
addRequestHeader("Cookie", cookie)
}
val manager: DownloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadId = manager.enqueue(downloadRequest)
registerReceiver(
object: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.w("onReceive", "${intent?.action}")
if (intent !== null && DownloadManager.ACTION_DOWNLOAD_COMPLETE == intent.action) {
val cursor = manager.query(DownloadManager.Query().apply{ setFilterById(downloadId) })
if (cursor.moveToFirst()) {
Log.w("onReceive", "cursor moved")
val downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
val downloadLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
val downloadMimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE))
Log.w("onReceive", "$downloadStatus $downloadLocalUri $downloadMimeType")
if (downloadStatus == DownloadManager.STATUS_SUCCESSFUL && downloadLocalUri !== null) {
val viewIntent = Intent(Intent.ACTION_VIEW).apply {
this.setDataAndType(Uri.parse(downloadLocalUri), downloadMimeType)
}
if (viewIntent.resolveActivity(packageManager) !== null) {
startActivity(
Intent.createChooser(viewIntent, "Choose app")
)
} else {
Toast.makeText(
context,
"No app available that can open file",
Toast.LENGTH_SHORT
)
.show()
}
}
}
}
}
},
IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
)
}
}
通过登录此代码,我可以确认我正在从 WebView 中获取 cookie。
有没有更好的方法来处理这个问题? 如果没有,我如何确定下载失败的原因? 另外,我做错了什么?
理想情况下,我还可以下载该文件,并确保在用户查看完 PDF 后将其删除。
你可以在加载 webview 的内容之前尝试这样的事情。
fun setCookies() {
val cookieManager = CookieManager.getInstance()
val cookieString = "your_cookie_here"
cookieManager.setCookie("domain_name_of_the_dowload_url", cookieString)
cookieManager.setAcceptThirdPartyCookies(your_webview_here, true)
}
事实证明,我检索 cookie 的方式是错误的,它最终剥离了密钥。 为了将来参考,在下载请求上设置 cookie 非常简单,使用:
addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.