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.
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)
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With