Nathan Kleinschmidt
05/01/2022, 3:13 PMclient = HttpClient(Android) {
install(JsonFeature) {
serializer = KotlinxSerializer()
}
}
The migration guide says to use the content negotiation plugin, but there are no examples of how to do this on Android that I can see.Dominaezzz
05/01/2022, 3:19 PMinstall(ContentNegotiation) { json() }
Amit
05/01/2022, 3:20 PMNathan Kleinschmidt
05/01/2022, 5:27 PMimplementation("io.ktor:ktor-client-content-negotiation:$ktor_version")
Nathan Kleinschmidt
05/02/2022, 3:09 AMjava.lang.IllegalStateException: No request transformation found:
thrown by this function:
val response = client
.post(HttpRoutes.LOGIN) {
contentType(ContentType.Application.Json)
setBody(loginRequest) // <- this line fails
}
where client : HttpClient
and loginRequest
is
@Serializable
data class LoginRequest(
val email : String,
val password : String
)
Am I not serializing the request correctly?
Apparently not - the setBody
call needs to instead be:
setBody(Json.encodeToString(LoginRequest.serializer(), loginRequest))
Nathan Kleinschmidt
05/02/2022, 4:19 AM.body()
method:
val userData : UserData = client
.post(HttpRoutes.LOGIN) {
contentType(ContentType.Application.Json)
setBody(Json.encodeToString(LoginRequest.serializer(), loginRequest))
}
.body<UserData>()
This fails with the error:
io.ktor.client.call.NoTransformationFoundException: No transformation found: class io.ktor.utils.io.ByteBufferChannel -> class UserData
Why is it ByteBufferChannel and not a Json or text?Dominaezzz
05/02/2022, 9:29 AMNathan Kleinschmidt
05/02/2022, 12:32 PMfun create() : AuthService {
return AuthServiceImpl(
client = HttpClient(Android) {
install(ContentNegotiation) {
json()
}
}
)
}
Nathan Kleinschmidt
05/02/2022, 1:40 PMContent-Type
header is indeed text/plain; charset=UTF-8
where I would have expected application/json
. My server is running Ktor 2.0, and the response is sent using
call.respond(result.statusCode, ResponseSerializer.encodeToString(result))
The docs say that content-type gets set automatically by serialization. Is it possible to set this manually or override the default?Nathan Kleinschmidt
05/02/2022, 7:48 PM.body()
explicitly, instead of just passing a type argument as the docs suggest.
This works:
val userData = Json.decodeFromString(
client
.post(HttpRoutes.LOGIN) {
contentType(ContentType.Application.Json)
setBody(Json.encodeToString(LoginRequest.serializer(), loginRequest))
}
.body()
) as UserData
This does not work:
val userData : UserData = client
.post(HttpRoutes.LOGIN) {
contentType(ContentType.Application.Json)
setBody(Json.encodeToString(LoginRequest.serializer(), loginRequest))
}
.body<UserData>()
I’m not really sure what the difference is, but body()
is not able to either parse or cast the Json string from the response.caique
05/28/2023, 9:16 AMNero Nguyễn
02/27/2024, 4:34 AMinstall(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
})
}
not
install(ContentNegotiation) {
Json {
prettyPrint = true
isLenient = true
}
}