Hi guys, I’m having an issue implementing ktor-cli...
# ktor
a
Hi guys, I’m having an issue implementing ktor-client on Android, using OkHttp and Gson. When I try to do a POST call with a body object, it gives me a ClassCastException:
Copy code
java.lang.ClassCastException: be.gekrabbel.ktortest.MyCustomObject cannot be cast to io.ktor.client.call.HttpClientCall
        at io.ktor.client.HttpClient.execute(HttpClient.kt:151)
        at io.ktor.client.call.HttpClientCallKt.call(HttpClientCall.kt:80)
        at be.gekrabbel.ktortest.MainActivity.callDoesntWork(MainActivity.kt:63)
        at be.gekrabbel.ktortest.MainActivity$onCreate$1.invokeSuspend(MainActivity.kt:41)
The strange thing is that when I use a String as body, everything works. My code:
Copy code
private val httpClient: HttpClient by lazy {
        HttpClient(OkHttp) {

            install(JsonFeature) {
                serializer = GsonSerializer()
            }
        }
    }

    private suspend fun callDoesntWork() {
        val call: HttpClientCall = httpClient.call {
            method = <http://HttpMethod.Post|HttpMethod.Post>

            url(Url("<https://google.com>"))

            body = MyCustomObject(message = "Hello World")
        }

        val response: String = try {
            call.response.receive()
        } catch (e: BadResponseStatusException) {
            "Error ${e.statusCode.value}"
        }
        println(response)
    }
The full source code in a sample project: https://github.com/Arne517/ktor-test/blob/master/app/src/main/java/be/gekrabbel/ktortest/MainActivity.kt
e
Forbidden
a
You mean you can’t access the link to the sample project? Or that it’s not the correct way to send a body?
e
Link was broken, now it’s ok
You could set content type explicit to force the conversion with json feature:
contentType(ContentType.Application.Json)
a
That works, thanks!