kotlin - KTOR - 在 POST 路由中解压缩文件
问题描述
我想解压缩在 Ktor(bloc rounting)中的 http 查询(内容类型:应用程序/x-gzip)的正文中发送的文件 zip。我试过这个:
val zip_received=call.receiveStream() val incomingContent = GZIPInputStream(zip_received).toByteReadChannel()
但我得到了这个错误:
java.lang.IllegalStateException:不允许在此调度程序上获取阻塞原语。考虑使用异步通道或使用 withContext(Dispatchers.IO) { call.receive().use { ... } } 代替。
我无法编写这样的功能。我可以帮忙吗?
谢谢
解决方案
您可以使用以下代码将 GZip 未压缩请求正文读取为字符串:
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.application.*
import io.ktor.request.*
import io.ktor.routing.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.InputStream
import java.util.zip.GZIPInputStream
fun main(args: Array<String>) {
embeddedServer(Netty, port = 9090) {
routing {
post("/") {
withContext(Dispatchers.IO) {
call.receive<InputStream>().use { stream ->
val gzipStream = GZIPInputStream(stream)
val uncompressedBody = String(gzipStream.readAllBytes())
println(uncompressedBody)
}
}
}
}
}.start()
}
推荐阅读
- python - 从 JSON 中获取嵌套的值 - python
- lisp - 使用 entmod 修改线实体
- r - geom_freqpoly 从零以下开始
- ios - RxSwift 不会将数据从一个 ViewController 推回另一个
- azure - 在 Azure 存储上启用静态网站未显示在选项列表中
- android - buildSrc 中自定义 gradle 插件中的类不会打包到 apk 中
- java - 是这个错误org/apache/commons/logging/LogFactory java.lang.NoClassDefFoundError的Logger类方法的模拟解决方案吗?
- java - Google Cloud SQL api export csv:自定义分隔符,处理“N”值并设置 utf8mb64
- list - raku 从头到尾做转子的更好方法是什么?
- magento - Magento 2 + WHM + SSL + Varnish 配置问题