Ktor HTTP客户端 - 请求进度

8
如何在Ktor http客户端中监控请求进度?
例如:我有这样的请求:
val response = HttpClient().get<String>("https://stackoverflow.com/")

我希望能够像这样使用进度条来监控请求进度:

fun progress(downloaded: Long, contentLength: Long) {
    // Update progress bar or whatever
}

我该如何设置progress()被HttpClient调用?
编辑:这是Kotlin跨平台项目。相关依赖包括:
implementation 'io.ktor:ktor-client-core:1.2.5'
implementation 'io.ktor:ktor-client-cio:1.2.5'
2个回答

6
自Ktor 1.6开始,您可以使用HttpRequestBuilder暴露的onDownload扩展函数来响应下载进度更改:
val channel = get<ByteReadChannel>("https://ktor.io/") {
    onDownload { bytesSentTotal, contentLength ->
        println("Received $bytesSentTotal bytes from $contentLength")
    }
}

还有onUpload函数可用于显示上传进度:

onUpload { bytesSentTotal, contentLength ->
    println("Sent $bytesSentTotal bytes from $contentLength")
}

以下是 Ktor 文档中的可运行示例:


1

如何将下载进度发送到Flow?

我想通过Flow观察下载进度,因此我编写了以下函数:

suspend fun downloadFile(file: File, url: String): Flow<Int>{
        val client = HttpClient(Android)
        return flow{
            val httpResponse: HttpResponse = client.get(url) {
                onDownload { bytesSentTotal, contentLength ->
                    val progress = (bytesSentTotal * 100f / contentLength).roundToInt()
                    emit(progress)
                }
            }
            val responseBody: ByteArray = httpResponse.receive()
            file.writeBytes(responseBody)
        }
}

但是 onDownload 只会被调用一次。如果我删除 emit(progress) 它将正常工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接