Kotlin Ktor http客户端-请求进度
如何监视Ktor http客户端中的请求进度 例如:我有这样的请求:Kotlin Ktor http客户端-请求进度,kotlin,ktor,Kotlin,Ktor,如何监视Ktor http客户端中的请求进度 例如:我有这样的请求: val response = HttpClient().get<String>("https://stackoverflow.com/") fun progress(downloaded: Long, contentLength: Long) { // Update progress bar or whatever } 如何设置HttpClient调用的progress() 编辑:这是Kotlin多平台
val response = HttpClient().get<String>("https://stackoverflow.com/")
fun progress(downloaded: Long, contentLength: Long) {
// Update progress bar or whatever
}
如何设置HttpClient调用的progress()
编辑:这是Kotlin多平台项目。相关依赖项包括:
implementation 'io.ktor:ktor-client-core:1.2.5'
implementation 'io.ktor:ktor-client-cio:1.2.5'
在从Ktor 1.6.0开始的Ktor中,您可以使用
HttpRequestBuilder
公开的扩展功能对下载进度更改作出反应:
val通道=获取(“https://ktor.io/") {
onDownload{bytesSentTotal,contentLength->
println(“从$contentLength接收到$bytesSentTotal字节”)
}
}
还有一个功能可用于显示上载进度:
onUpload{bytesSentTotal,contentLength->
println(“从$contentLength发送的$bytesSentTotal字节”)
}
以下是Ktor文档中的可运行示例:
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)
}
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)
}
}
...
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)
...