如何从WebView打开PDF时,PDF是由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))

相关内容