本文接上一篇博文:OkHttp初探:如何使用OkHttp进行Get或Post请求?Kotlin版本。
通用模块封装
这里封装一些通用的代码,先知道一下就可以了。
fun log(vararg msg: Any?) {
val nowTime = SimpleDateFormat("HH:mm:ss:SSS").format(System.currentTimeMillis())
println("$nowTime [${Thread.currentThread().name}] ${msg.joinToString(" ")}")
}
internal typealias ProgressBlock = (state: DownloadState) -> Unit
sealed class DownloadState {
object UnStart : DownloadState()
class Progress(var totalNum: Long, var current: Long) : DownloadState()
class Complete(val file: File?) : DownloadState()
class Failure(val e: Throwable?) : DownloadState()
class FileExistsNoDownload(val file: File?) : DownloadState()
}
下载文件,带进度,一般封装
fun downloadFile(url: String, destFileDirName: String, progressBlock: ProgressBlock) {
var state: DownloadState = DownloadState.UnStart
progressBlock(state)
val file = File(destFileDirName)
val parentFile = file.parentFile
if (!parentFile.exists()) {
parentFile.mkdirs()
}
if (file.exists()) {
state = DownloadState.FileExistsNoDownload(file)
progressBlock(state)
return
} else {
file.createNewFile()
}
val okHttpClient = OkHttpClient()
val request = Request.Builder().url(url).build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
state = DownloadState.Failure(e)
progressBlock(state)
}
override fun onResponse(call: Call, response: Response) {
response.use { res ->
var totalLength = 0L
val bytes = ByteArray(2048)
val fileOutputStream = FileOutputStream(file)
res.body?.also { responseBody ->
totalLength = responseBody.contentLength()
}?.byteStream()?.let { inputStream ->
try {
var currentProgress = 0L
var len = 0
state = DownloadState.Progress(totalLength, currentProgress)
do {
if (len != 0) {
currentProgress += len
fileOutputStream.write(bytes)
}
(state as DownloadState.Progress).current = currentProgress
progressBlock(state)
len = inputStream.read(bytes, 0, bytes.size)
} while (len != -1)
state = DownloadState.Complete(file)
progressBlock(state)
} catch (e: Exception) {
state = DownloadState.Failure(e)
progressBlock(state)
} finally {
inputStream.close()
fileOutputStream.close()
}
}
}
}
})
}
使用
downloadFile(
"https://dldir1.qq.com/weixin/Windows/WeChatSetup.exe",
"download/WeChatSetup.exe"
) { state: DownloadState ->
when (val s = state) {
is DownloadState.Complete -> log("下载完成 文件路径为 ${s.file?.absoluteFile}")
is DownloadState.Failure -> log("下载失败 ${s.e?.message}")
is DownloadState.FileExistsNoDownload -> log("已经存在 ${s.file?.absoluteFile}")
is DownloadState.Progress -> log("下载中 ${(s.current.toFloat() / s.totalNum) * 100}%")
DownloadState.UnStart -> log("下载未开始")
}
}
使用flow封装
对于上述封装使用起来没有问题,但是如果在android上面要把进度显示出来的话,就需要手动切换到UI线程了。不太方便。既然都用kotlin了,那么为什么不解除协程Flow封装呢?
所以,下面基于Flow的封装就来了。直接切换到Main线程,美滋滋。
知识储备: Kotlin:Flow 全面详细指南,附带源码解析。 Flow : callbackFlow使用心得,避免踩坑!
fun downloadFileUseFlow(url: String, destFileDirName: String) = callbackFlow<DownloadState> {
var state: DownloadState = DownloadState.UnStart
send(state)
val file = File(destFileDirName).also { file ->
val parentFile = file.parentFile
if (!parentFile.exists()) {
parentFile.mkdirs()
}
if (file.exists()) {
state = DownloadState.FileExistsNoDownload(file)
send(state)
close()
return@callbackFlow
} else {
file.createNewFile()
}
}
val okHttpClient = OkHttpClient().newBuilder()
.dispatcher(dispatcher)
.writeTimeout(30, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.MINUTES)
.build()
val request = Request.Builder()
.url(url)
.build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
state = DownloadState.Failure(e)
this@callbackFlow.trySendBlocking(state)
close()
}
override fun onResponse(call: Call, response: Response) {
val body = response.body
if (response.isSuccessful && body != null) {
val totalNum: Long = body.contentLength()
var currentProgress: Long = 0L
var len = 0
response.use {
val outputStream = file.outputStream()
val byteStream = body.byteStream()
try {
val bates = ByteArray(2048)
state = DownloadState.Progress(totalNum, currentProgress)
do {
if (len != 0) {
currentProgress += len
outputStream.write(bates)
}
(state as DownloadState.Progress).current = currentProgress
this@callbackFlow.trySendBlocking(state)
len = byteStream.read(bates, 0, bates.size)
} while (len != -1)
state = DownloadState.Complete(file)
this@callbackFlow.trySendBlocking(state)
} catch (e: Exception) {
state = DownloadState.Failure(e)
this@callbackFlow.trySendBlocking(state)
} finally {
outputStream.close()
byteStream.close()
this@callbackFlow.close()
}
}
} else {
state = DownloadState.Failure(Exception(response.message))
this@callbackFlow.trySendBlocking(state)
close()
}
}
})
awaitClose {
log("callbackFlow关闭 .")
}
}
.buffer(Channel.CONFLATED)
.flowOn(Dispatchers.Default)
.catch { e ->
emit(DownloadState.Failure(e))
}
使用
runBlocking(Dispatchers.Main) {
downloadFileUseFlow(
"https://dldir1.qq.com/weixin/Windows/WeChatSetup.exe",
"download/WeChatSetup.exe"
).onEach { downloadState ->
when (downloadState) {
is DownloadState.Complete -> log("下载完成 文件路径为 ${downloadState.file?.absoluteFile}")
is DownloadState.Failure -> log("下载失败 ${downloadState.e?.message}")
is DownloadState.FileExistsNoDownload -> log("已经存在 ${downloadState.file?.absoluteFile}")
is DownloadState.Progress -> log("下载中 ${(downloadState.current.toFloat() / downloadState.totalNum) * 100}%")
DownloadState.UnStart -> log("下载未开始")
}
}.launchIn(this)
.join()
}
以上就是博主提供的两种简单的封装方式了。
后面会陆续推出OkHttp高阶使用,以及OkHttp源码分析博客。觉得不错关注博主哈~😎 创作不易,如有帮助一键三连咯🙆?♀?。欢迎技术探头噢!
|