【发布时间】:2021-04-18 04:07:53
【问题描述】:
如何使用kotlin和ktor在POST请求中添加JSON字符串?
打印出从文件中读取的Json字符串,甚至在客户端用Kotlin构造的字符串,内容看起来像JSON。
服务器仍然无法将字符串识别为 JSON,当我在服务器中打印它时,每个双倍配额都被反斜杠。
客户端显然添加了反斜杠,因此请求没有按应有的格式格式化。
客户端 Kotlin - Ktor 代码:
import com.google.gson.*
import io.ktor.client.*
import io.ktor.http.*
...
val client = HttpClient(OkHttp) {
install(JsonFeature) {
serializer = GsonSerializer()
}
}
val fileContent = MyClass::class.java.getResource("myfile").readText()
println("fileContent string = $fileContent")
val out = client.post<String> {
url(url)
contentType(ContentType.Application.Json)
body = fileContent
}
打印出来的样子是这样的:
{ "name": "myname", "value": "myvalue" }
但是服务器(我使用 hookbin 来真正打印出没有杰克逊转换的数据)打印出来:
{ \"name\": \"myname\", \"value\": \"myvalue\" }
【问题讨论】:
标签: json http kotlin post ktor