【发布时间】:2021-07-31 19:29:36
【问题描述】:
我想在 kotlin 中使用 ok HTTP 从 url 下载 pdf。我没有在协程中找到正确的解决方案是如何完成的。下载后我想存储在设备中并在 pdf 查看器中显示。当用户关闭活动时,存储文件会自动从内部存储中删除。有谁知道这是怎么做到的吗。提前致谢
class FileDownloader {
companion object {
private const val BUFFER_LENGTH_BYTES = 1024 * 8
private const val HTTP_TIMEOUT = 30
}
private var okHttpClient: OkHttpClient
init {
val okHttpBuilder = okHttpClient.newBuilder()
.connectTimeout(HTTP_TIMEOUT.toLong(), TimeUnit.SECONDS)
.readTimeout(HTTP_TIMEOUT.toLong(), TimeUnit.SECONDS)
this.okHttpClient = okHttpBuilder.build()
}
fun download(url: String, file: File): {
val request = Request.Builder().url(url).build()
val response = okHttpClient.newCall(request).execute()
val body = response.body
val responseCode = response.code
if (responseCode >= HttpURLConnection.HTTP_OK &&
responseCode < HttpURLConnection.HTTP_MULT_CHOICE &&
body != null) {
val length = body.contentLength()
body.byteStream().apply {
file.outputStream().use { fileOut ->
var bytesCopied = 0
val buffer = ByteArray(BUFFER_LENGTH_BYTES)
var bytes = read(buffer)
while (bytes >= 0) {
fileOut.write(buffer, 0, bytes)
bytesCopied += bytes
bytes = read(buffer)
}
}
}
} else {
throw IllegalArgumentException("Error occurred when do http get $url")
}
}
}
}
这也不起作用,当用户关闭活动时如何使用协程并删除文件。
【问题讨论】:
标签: android kotlin httpurlconnection okhttp kotlin-coroutines