Как отобразить pdf перейдя по url передав токен в header?

Имеется url (../documents?id=5&fin_id=1&name=finance&type=pdf) и токен. Нужно открыть pdf по url передав токен.

Я использую webview, передаю корректный header, в postman приходит pdf, у меня белый экран.

Перейдя по ссылке с header, сайт выдает pdf файл:

%PDF-1.7
1 0 obj
<< /Type /Catalog
/Outlines 2 0 R
/Pages 3 0 R >>
endobj
2 0 obj
...

Я пробовал:

presenter.onAttach(this)

with(webView.settings) {
    javaScriptEnabled = true
}

val docUrl = intent.extras!!.getString(OrderFragment.ORDER_DOC)

val header:Map<String,String> = hashMapOf("Authorization" to "Bearer ${presenter.accessToken()}")

webView.loadUrl(docUrl, header)

Отлавливаю адрес, он корректный.

webView.webViewClient = object : WebViewClient() {
    override fun onLoadResource(view: WebView?, url: String?) {
        super.onLoadResource(view, url)
        Log.e("TAG", "url: $url")
    }
}

Пробовал добавить к url адрес на ридер pdf, тоже не получилось.

Через намерение открыть не получается, так как не нашел информацию как передать в него токен (который собственно все усложняет). Пробовал такое

val i = Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse(url), "application/pdf");
//но как передать сюда токен?
activity.startActivity(i)

Нужен любой возможный способ


Ответы (1 шт):

Автор решения: asprog_ii

Несколько часов поиска решения привели меня к самому оптимальному.

Я отправляю запрос по нужному url, передав необходимый header и по получению читаю поток.

Приведу ключевые моменты кода, может кому-то будет полезно:)

@Streaming
@GET
suspend fun performGetPdfFile(
    @Url url:String
): Response<ResponseBody>

При создании класса для чтения мне во многом помог ответ от сюда:

https://stackoverflow.com/questions/32878478/how-to-download-file-in-android-using-retrofit-library

class PdfOpenStreamHelper {
    @SuppressLint("CheckResult")
    fun openPdfFromStream(response: Response<ResponseBody>, activity: Activity) {
        Observable.fromCallable(object : Callable<File?> {
            @SuppressLint("CheckResult")
            @Throws(Exception::class)
            override fun call(): File? {

                val body = response.body() ?: return null
                var input: InputStream? = null
                try {
                    // download the file
                    input = body.byteStream()
                    val dir = File(activity.filesDir, "/shared_pdf")
                    dir.mkdir()
                    val file = File(dir, "name.pdf")
                    val output: OutputStream = FileOutputStream(file)
                    val data = ByteArray(1024)
                    var total: Long = 0
                    var count: Int = 0
                    while (input.read(data).also { count = it } != -1) {
                        total += count.toLong()
                        output.write(data, 0, count)
                    }
                    output.flush()
                    output.close()
                    input.close()
                    return file
                } catch (e: IOException) {
                    e.printStackTrace()
                } finally {
                    input?.close()
                }
                return null
            }
        })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                val authority = activity.applicationContext.packageName + ".fileprovider"
                val uriToFile: Uri = FileProvider.getUriForFile(activity, authority, it!!)
                val shareIntent = Intent(Intent.ACTION_VIEW)
                shareIntent.setDataAndType(uriToFile, "application/pdf")
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                if (shareIntent.resolveActivity(activity.packageManager) != null) {
                    activity.startActivity(shareIntent)
                }
            }
    }
}
→ Ссылка