Reputation: 51
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.
Upvotes: 4
Views: 10626
Reputation: 844
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)
}
})
}
Upvotes: 4
Reputation: 1477
Check out the official OkHttp's Recipes: https://square.github.io/okhttp/connections/
Upvotes: 1
Reputation: 200
Theres's a lot more to be done to achieve this, and I'm still working on achieving the same thing for PDFs, but here's some code that worked for me to download image files:
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/ergonomics/pdf_test");
myDir.mkdirs();
String fname = "TestPdf-01A.pdf";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
InputStream is = response.body().byteStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Just FYI ByteArrayBuffer is deprecated along with all the Apache stuff for networking in Android. But, theoretically, it works, and should be easy for you to follow.
Upvotes: -2