Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading pdf file using OKHTTP

I am using ok-http in my android application.

I have url of .pdf file which is coming from web-service.

I have to download pdf file on click event of ImageView. I have searched it on google but, couldn't find specific answer.

Please, provide me solution if anyone knows about it. Thanks.

like image 673
Jaimin Modi Avatar asked Aug 30 '25 16:08

Jaimin Modi


1 Answers

I use OKHttp to download PDFs with a function like this. The only difference with downloading a PDF and a json file is how you handle the response. I use response.body?.byteStream() for PDFs.

fun downloadPdf(context: Context, pdfUrl: String, completion: (Boolean) -> Unit) {

    val request = Request.Builder()
        .url(pdfUrl)
        .build()
    val client = OkHttpClient.Builder()
        .build()

    client.newCall(request).enqueue(object: Callback {

        override fun onResponse(call: Call, response: Response) {
            println("successful download")

            val pdfData = response.body?.byteStream()

           //At this point you can do something with the pdf data
           //Below I add it to internal storage

            if (pdfData != null) {

                try {
                    context.openFileOutput("myFile.pdf", Context.MODE_PRIVATE).use { output ->
                        output.write(pdfData.readBytes())
                    }

                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            completion(true)
        }

        override fun onFailure(call: Call, e: IOException) {

            println("failed to download")
            completion(true)
        }
    })
}
like image 94
iOS_Mouse Avatar answered Sep 02 '25 06:09

iOS_Mouse