我想知道如何才能惯用地浏览位于
Link
标题的下一页。
现在我需要手动提取它:
private fun getNextPageIfExists(link: String): String? =
if (link.contains(""">;rel="next",""")) {
link
.substringBefore(""">;rel="next",""")
.substringAfterLast("<")
} else {
null
}
并使用提取的 URI 调用
RestClient
。
请记住,根据 MDN,链接标头中可能存在可选的空格和引号,因此以下所有三个示例都是有效的(而只有第一个示例会被您的原始代码覆盖):
<https://example.com>;rel=next
<https://example.com>; rel=next
<https://one.example.com>;rel="next"
话虽这么说,这是我尝试通过逐渐分割和修剪输入字符串来使用
rel="next"
提取 url:
private val String.nextPage: String? get() =
this.splitAndTrim(",")
.mapNotNull {
// Separate the url from parameters
val (url, parameters) = it.splitAndTrim(";", limit = 2)
// Find the value of rel parameter
val relation = parameters
.splitAndTrim(";")
.map { it.splitAndTrim("=", limit = 2) }
.filter { (key, value) -> key == "rel" }
.map { (key, value) -> value.removeSurrounding("\"") }
.firstOrNull()
return@mapNotNull if (relation == "next") url else null
}.firstOrNull()?.removeSurrounding("<", ">") // And finally remove the brackets from url
private fun String.splitAndTrim(vararg delimiters: String, limit: Int = 0) = this
.split(*delimiters, limit = limit)
.map { it.trim() }