如何使用 Ktor 服务器向其他服务器发送 POST 请求?

Ton*_*ang 2 backend kotlin server ktor

我使用 IDEA 生成模板并注意到 Application.module 中的 runBlocking 如下:

    runBlocking {
    // Sample for making a HTTP Client request
        val message = client.post<JsonSampleClass> {
            url("http://127.0.0.1:8080/path/to/endpoint")
            contentType(ContentType.Application.Json)
            body = JsonSampleClass(hello = "world")
        }
   }
Run Code Online (Sandbox Code Playgroud)

但是当我这样写向另一个服务器(例如获取天气的服务器)发送 Post 请求时,我得到:

java.io.IOException:管道损坏

我不知道是我写错了还是写错了地方。

Iso*_*mov 5

当然,日期类值得 JsonSampleClass,您需要像过度增长响应中那样更改此类或使用 HttpResponse。例子:

runBlocking {
// Sample for making a HTTP Client request
    val message = client.post<HttpResponse> { // or your data class
        url("url")
        contentType(ContentType.Application.Json)
        setBody(JsonSampleClass(hello = "world"))
    }
}
Run Code Online (Sandbox Code Playgroud)

https://ktor.io/docs/request.html#body