Denis Korchuganov
Denis Korchuganov

Reputation: 163

How can I parse HTTP headers using ktor

I'm using ktor 1.5.3 HTTP client and wondering how can I deserialize HTTP response headers into a list of LinkHeader values. I have the following value in my code:

response.headers.getAll("Link")

which is a list of strings, and I want to get a value of type

List<LinkHeader>

UPDATED:

The details of my use-case:

I have a backend that uses the following response headers to manage pagination:

Link: <https://hostname/v2/issues?orderBy=updated&orderAsc=false&perPage=15>; rel="first"
Link: <https://hostname/v2/issues?orderBy=updated&orderAsc=false&page=2&perPage=15>; rel="prev"
Link: <https://hostname/v2/issues?orderBy=updated&orderAsc=false&page=4&perPage=15>; rel="next"
Link: <https://hostname/v2/issues?orderBy=updated&orderAsc=false&page=116922&perPage=15>; rel="last"

I just have to parse them to understand where is the last page

Upvotes: 2

Views: 2019

Answers (2)

Denis Korchuganov
Denis Korchuganov

Reputation: 163

As there is no accurate solution from Ktor, I've implemented a workaround from this article. The same do-while loop worked in my case as well. It makes a redundant API call for an empty last page but works.

Upvotes: 0

Aleksei Tirman
Aleksei Tirman

Reputation: 7079

Since there is not such functionality in Ktor right now, I've created this feature request to address your problem. As a workaround, you can use regular expressions for your particular case to parse headers' values:

data class Link(val url: Url, val rel: String)

fun parse(value: String): Link {
    val matches = Regex("""<(.+?)>;\s*rel="(.+?)"""").matchEntire(value) ?: throw Exception("Cannot parse Link header value $value")
    val (_, urlString, rel) = (matches.groupValues)
    return Link(URLBuilder(urlString).build(), rel)
}

Upvotes: 1

Related Questions