When using Json-feature in ktor-client to perform ...
# ktor
m
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
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
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
This is how Retrofit works, allows you to get result directly or response instance with result if you need additional information
👍 1
d
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())
}
👍 1
@e5l
e
Sure. I’ll try to add something like that soon.
👍 1
👏 2