spo*_*ant 8 kotlin ktor ktor-client
我正在使用Ktor 1.2.2,并且有一个 InputStream 对象,我想将其用作我接下来发出的 HttpClient 请求的主体。直到 Ktor 0.95 为止,这个InputStreamContent对象似乎就是这样做的,但它已在版本 1.0.0 中从 Ktor 中删除(遗憾的是无法弄清楚原因)。
我可以使用 ByteArrayContent 使其工作(请参见下面的代码),但我宁愿找到一个不需要将整个 InputStream 加载到内存中的解决方案......
ByteArrayContent(input.readAllBytes())
Run Code Online (Sandbox Code Playgroud)
此代码是一个简单的测试用例,模拟我想要实现的目标:
val file = File("c:\\tmp\\foo.pdf")
val inputStream = file.inputStream()
val client = HttpClient(CIO)
client.call(url) {
method = HttpMethod.Post
body = inputStream // TODO: Make this work :(
}
// [... other code that uses the response below]
Run Code Online (Sandbox Code Playgroud)
如果我遗漏了任何相关信息,请告诉我,
谢谢!
实现此目的的一种方法是创建OutgoingContent.WriteChannelContent的子类,并将其设置为发布请求的正文。
一个例子可能是这样的:
class StreamContent(private val pdfFile:File): OutgoingContent.WriteChannelContent() {
override suspend fun writeTo(channel: ByteWriteChannel) {
pdfFile.inputStream().copyTo(channel, 1024)
}
override val contentType = ContentType.Application.Pdf
override val contentLength: Long = pdfFile.length()
}
// in suspend function
val pdfFile = File("c:\\tmp\\foo.pdf")
val client = HttpClient()
val result = client.post<HttpResponse>("http://upload.url") {
body = StreamContent(pdfFile)
}
Run Code Online (Sandbox Code Playgroud)
Ktor 1.2.2 中唯一的 API(我发现...)可能会发送多部分请求,这需要您的接收服务器能够处理此请求,但它确实支持直接 InputStream。
来自他们的文档:
val data: List<PartData> = formData {
// Can append: String, Number, ByteArray and Input.
append("hello", "world")
append("number", 10)
append("ba", byteArrayOf(1, 2, 3, 4))
append("input", inputStream.asInput())
// Allow to set headers to the part:
append("hello", "world", headersOf("X-My-Header" to "MyValue"))
}
Run Code Online (Sandbox Code Playgroud)
话虽这么说,我不知道它内部是如何工作的,并且可能仍然加载整个流到内存中。
readBytes 方法是缓冲的,因此不会占用整个内存。
inputStream.readBytes()
inputStream.close()
Run Code Online (Sandbox Code Playgroud)
请注意,您仍然需要使用 InputStream 上的大多数方法来关闭 inputStream
Ktor 来源: https: //ktor.io/clients/http-client/call/requests.html#the-submitform-and-submitformwithbinarydata-methods
Kotlin 来源:https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-input-stream/index.html
归档时间: |
|
查看次数: |
6331 次 |
最近记录: |