Ktor HTTP客户端-请求进度 [英] Ktor http client - request progress
问题描述
如何在Ktor http客户端中监视请求进度?
How do I monitor request progress in Ktor http client?
例如:我有这样的要求:
For example: I have request like this:
val response = HttpClient().get<String>("https://stackoverflow.com/")
并且我想用进度条监视请求进度:
and I want to monitor request progress with progress bar like this:
fun progress(downloaded: Long, contentLength: Long) {
// Update progress bar or whatever
}
如何设置progress()
由HttpClient调用?
How do I set progress()
to be called by HttpClient?
edit:这是Kotlin Multiplatform项目.相关的依赖项是:
edit: This is Kotlin Multiplatform project. Relevant dependencies are:
implementation 'io.ktor:ktor-client-core:1.2.5'
implementation 'io.ktor:ktor-client-cio:1.2.5'
推荐答案
在 Ktor <1.3.2 中,您可以通过请求ByteReadChannel而不是String来监视下载进度.
In Ktor<1.3.2, you can monitor your download progress by requesting a ByteReadChannel instead of a String.
缺点是,这样一来,您将无法获得文件的内容大小,但是可以通过单独的HEAD请求轻松获得(如果下载的文件足够大,则不会增加太多开销)需要进度监控)
The downside is, that this way you won't get the content size of your file, but it can be easily obtained with a separate HEAD request (which should not add too much overhead if you are downloading file that is large enough to require progress monitoring)
val contentLength = // need to get via HEAD reqeuest
suspend fun download() {
val url = "https://stackoverflow.com/"
val client = HttpClient()
val channel = client.get<ByteReadChannel>(url)
var total = 0
var readBytes:Int
var buffer = ByteArray(contentLength)
do {
readBytes = channel.readAvailable(buffer, total, 4096 )
total+=readBytes
progress(total, contentLength)
} while (readBytes>0)
val response = String(buffer)
}
对于 Ktor> 1.3.2 ,采用推荐的方式监视请求进度是使用 HttpStatement ,例如:
For Ktor>1.3.2 the recommended way of monitoring the request progress is to use HttpStatement, e.g.:
suspend fun download() {
val client = HttpClient()
val builder = HttpRequestBuilder().apply {
url("https://stackoverflow.com")
}
val httpStatement = HttpStatement(builder, client)
httpStatement.execute { response: HttpResponse ->
// Response is not downloaded here
val channel = response.receive<ByteReadChannel>()
val contentLength = response.contentLength()
requireNotNull(contentLength) {"Header needs to be set by server"}
var total = 0
var readBytes:Int
var buffer = ByteArray(contentLength)
do {
readBytes = channel.readAvailable(buffer, total, 4096 )
total+=readBytes
progress(total, contentLength)
} while (readBytes>0)
val response = String(buffer)
}
}
当然,如果下载大文件,使用较小的缓冲区会更明智,然后直接将其写入某个文件,例如:
Of course, if downloading a large file it would be more sensible use a smaller buffer, and directly write it to some file, e.g.:
...
var buffer = ByteArray(4096)
do {
readBytes = channel.readAvailable(buffer, 0, 4096 )
total+=readBytes
writeToFile(buffer, readBytes) // do something sensible with the read bytes
progress(total, response.contentLength())
} while (readBytes>0)
...
这篇关于Ktor HTTP客户端-请求进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!