我在我的安卓应用中使用了ok-http。
我有一个来自web服务的.pdf文件的url。
我需要在ImageView的点击事件中下载pdf文件。我已经在谷歌上搜索过,但是没有找到具体的答案。
如果有人知道,请提供解决方案。谢谢。
我在我的安卓应用中使用了ok-http。
我有一个来自web服务的.pdf文件的url。
我需要在ImageView的点击事件中下载pdf文件。我已经在谷歌上搜索过,但是没有找到具体的答案。
如果有人知道,请提供解决方案。谢谢。
我使用 OKHttp 下载 PDF 的函数类似于此。与下载 json 文件的唯一区别在于如何处理响应。对于 PDF,我使用 response.body?.byteStream()。
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)
}
})
}
要实现这个目标还有很多工作要做,我仍在努力为PDF文件实现同样的功能,但是这里有一些代码可以帮助我下载图像文件:
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();
仅供参考,ByteArrayBuffer 在 Android 中的所有 Apache 网络相关功能已弃用。但是从理论上讲,它可以工作,并且应该很容易跟进。