Ktor http 客户端 - 请求进度

Ktor http client - request progress

如何在 Ktor http 客户端中监控请求进度?

例如:我有这样的请求:

val response = HttpClient().get<String>("https://whosebug.com/")

我想用这样的进度条监控请求进度:

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

如何设置 progress() 由 HttpClient 调用?

编辑:这是 Kotlin Multiplatform 项目。相关依赖项是:

implementation 'io.ktor:ktor-client-core:1.2.5'
implementation 'io.ktor:ktor-client-cio:1.2.5'

从 Ktor 1.6.0 开始,您可以使用 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 文档中的可运行示例:

如何将下载进度发送到 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) 它将起作用。

@andrey-aksyonov