When using Json-feature in ktor-client to perform requests, we can do something like:
Copy code
val response = client.get<MyClass>(“<https://en.wikipedia.org/wiki/Main_Page”>)
This will return convert the returned Json to MyClass. However, this won’t allow us to get additional info such as return status code etc. Is there a way to get around this?
d
Deactivated User
08/21/2018, 11:03 AM
So what you would want is a function that returns a class containing the typed instance + a instance with the response to check headers and the status of the response?
m
Mohit Gurumukhani
08/21/2018, 3:41 PM
Yeah I mean we could have http response take in a class using something like:
Copy code
val response = client.get<HttpResponse<Myclass>>(“<https://en.wikipedia.org/wiki/Main_Page”>)
Where MyClass defines serialized return type along with body maybe?
👍 1
g
gildor
08/22/2018, 5:57 AM
This is how Retrofit works, allows you to get result directly or response instance with result if you need additional information
👍 1
d
Deactivated User
08/22/2018, 9:33 AM
I guess that would be a reasonable thing to add. Maybe a feature could enable this by injecting something in the pipeline so it is compatible with other transformers.
But in the meantime, you can add something like this:
Copy code
data class HttpClientTypedResponse<T>(val response: HttpResponse, val instance: T) : HttpResponse by response
suspend inline fun <reified T> HttpClient.getTyped(
url: String = "<http://127.0.0.1:8080/>",
body: Any = EmptyContent,
noinline block: HttpRequestBuilder.() -> Unit = {}
): HttpClientTypedResponse<T> {
val call = call {
url(url)
method = HttpMethod.Get
this.body = body
block()
}
return HttpClientTypedResponse(call.response, call.receive())
}