https://kotlinlang.org logo
#ktor
Title
# ktor
s

Sheroz Nazhmudinov

12/03/2020, 4:33 PM
Hi 👋 I’m playing with ktor on Android platform, to see how it works. I managed to test the
get
request, but i’m hitting
MissingFieldException
when trying out
post
. Can smbd please check what I might be doing wrong? Thanks in advance! Some code snippets:
Copy code
@Serializable
data class RegistrationParams(
    val name: String,
    val job: String
)

@Serializable
data class RegistrationResponse(
    @SerialName("name") val name: String,
    @SerialName("job") val job: String,
    @SerialName("id") val id: String,
    @SerialName("createdAt") val createdAt: String
)

val httpClient = HttpClient(Android) {
        install(JsonFeature) {
            val json = Json { ignoreUnknownKeys = true }
            serializer = KotlinxSerializer(json = json)
        }
    }

suspend fun samplePostRequest(): RegistrationResponse = <http://client.post|client.post>(
        urlString = "<https://reqres.in/api/users>",
    ) {
        body = Json.encodeToString(
            RegistrationParams.serializer(),
            RegistrationParams(
                name = "Neo",
                job = "The Chosen One"
            )
        )
    }
The error message says:
Field 'name' is required, but it was missing
j

Joost Klitsie

12/03/2020, 5:05 PM
I think you can just put in
body = RegistrationParams(name = "Neo", job = "The Chosen One")
because the client should be able to serialize it
perhaps put the contenttype next to it:
Copy code
contentType(ContentType.Application.Json)
s

Sheroz Nazhmudinov

12/03/2020, 5:10 PM
👍 thank you very much, it worked.
💯 1
4 Views