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

arne.stockmans

03/05/2019, 3:35 PM
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

e5l

03/06/2019, 7:15 AM
Forbidden
a

arne.stockmans

03/06/2019, 8:57 AM
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

e5l

03/06/2019, 8:58 AM
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

arne.stockmans

03/06/2019, 9:38 AM
That works, thanks!