Tony Dang
Tony Dang

Reputation: 27

How can I send POST request to other server with Ktor server?

I use IDEA to generate a template and notice that runBlocking in Application.module like:

    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")
        }
   }

But when I write like that to send a Post request to another server (such as a server to get weather), I got:

java.io.IOException: Broken pipe

I don't know that if I write it in a wrong way or just in a wrong place.

Upvotes: 2

Views: 9576

Answers (1)

Isoq Hakimov
Isoq Hakimov

Reputation: 150

for sure, the date class is worth JsonSampleClass, you need to change this class as in the overgrowth response or use HttpResponse. Example:

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"))
    }
}

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

Upvotes: 5

Related Questions