【问题标题】:How to send JSON String with POST using ktor kotlin?如何使用 ktor kotlin 通过 POST 发送 JSON 字符串?
【发布时间】: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


    【解决方案1】:

    解决方案是向 HTTP POST 请求传递 JSON 对象而不是 String 对象。当您打印它们时,它们看起来是一样的,但它们当然不会被 JVM 同等解释。所以,我们只需要解析字符串。我使用 GSON 库。 添加 JsonParser -> parseString 方法并在客户端使用它的对象:

    import com.google.gson.JsonParser    
    
    val fileContent = MyClass::class.java.getResource("myfile").readText()
    println("fileContent string = $fileContent")
    
    var bodyAsJsonObject = JsonParser.parseString(fileContent).asJsonObject
    
    println("bodyAsJsonObject = $bodyAsJsonObject")
    
    val out = client.post<String> {
        url(url)
        contentType(ContentType.Application.Json)
        body =  bodyAsJsonObject
    }
    

    【讨论】:

    • 当我做同样重要的事情时,它在分配给“body”时崩溃。我的代码有什么不同?
    • val jsonBody = JSONObject() val response: HttpResponse = httpClient.post(URLAuthenticateProfile) { headers { append(HttpHeaders.ContentType, "application/json") append(HttpHeaders.CacheControl, "no-cache ") } contentType(ContentType.Application.Json) body = jsonBody }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    相关资源
    最近更新 更多