我有以下使用curl效果很好的示例:
curl -X 'POST' \
'https://example.com/rest/someservice?oauth_token=<token>' \
-H 'accept: application/json' \
-H 'Content-Type: multipart/form-data' \
-F 'file=@docs_recognize_ok.jpg;type=image/jpeg' \
-F 'meta={
"images": [
{
"name": "file"
}
]
}'
不知道如何使用 Java/Kotlin 中的 ktor 客户端来处理它?
目前我正在尝试将其处理为:
val json = "{\n" +
" \"images\": [\n" +
" {\n" +
" \"name\": \"file\"\n" +
" }\n" +
" ]\n" +
"}"
val filesList = mutableListOf<PartData>()
val partData = formData {
append(key = "meta", value = json, headers = Headers.build {
append(HttpHeaders.ContentType, "application/json; charset=utf-8")
})
request.images.forEach { file ->
append(
"file",
InputProvider { File(file.imageFileName).inputStream().asInput() },
Headers.build {
append(HttpHeaders.ContentType, "image/jpeg")
}
)
}
}
filesList.addAll(partData)
httpClient.post("rest/someservice") {
setBody(MultiPartFormDataContent(parts = filesList))
parameters {
append("oauth_token", apiKey)
}
}
有什么想法吗?
有关使用 Ktor 客户端发送多部分/表单数据请求的信息可以在 文档中找到。 这是您的curl命令或多或少的直接翻译:
val client = HttpClient(CIO)
client.post("https://example.com/rest/someservice?oauth_token=<token>") {
header(HttpHeaders.Accept, "application/json")
setBody(
MultiPartFormDataContent(
formData {
append(
"meta", """{
"images": [
{
"name": "file"
}
]
}""".trimIndent()
)
append("file", File("docs_recognize_ok.jpg").readBytes(), Headers.build {
append(HttpHeaders.ContentType, "image/jpeg")
append(HttpHeaders.ContentDisposition, "filename=\"docs_recognize_ok.jpg\"")
})
},
)
)
}