简体   繁体   English

当 PDF 受 cookie 保护时,如何从 WebView 打开 PDF?

[英]How to open a PDF from WebView when PDF is secured by a cookie?

I am trying to download and open a PDF file from my WebView.我正在尝试从我的 WebView 下载并打开一个 PDF 文件。 I have tried retrieving the cookie from the WebView, and setting the cookie on a DownloadManager.Request.我尝试从 WebView 检索 cookie,并在 DownloadManager.Request 上设置 cookie。 When my BroadCastReceiver is triggered, the download status states that it has failed.当我的 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)
                )
            }
}

Through the logging in this code, I can confirm that I am getting the cookie out of the WebView.通过登录此代码,我可以确认我正在从 WebView 中获取 cookie。

Is there a better approach to handle this?有没有更好的方法来处理这个问题? If not, how do I determine why the download is failing?如果没有,我如何确定下载失败的原因? Also, what am I doing wrong?另外,我做错了什么?

Ideally, I would also be able to download the file, and ensure it is deleted after the user has finished viewing the PDF.理想情况下,我还可以下载该文件,并确保在用户查看完 PDF 后将其删除。

You could try something like this before loading the webview's content.你可以在加载 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)
}

It turned out that the way I was retrieving the cookie was wrong, it ended up stripping out the key.事实证明,我检索 cookie 的方式是错误的,它最终剥离了密钥。 For future reference, it is quite simple to set the cookie on the download request, with:为了将来参考,在下载请求上设置 cookie 非常简单,使用:

addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM