Spring RestClient - 使用分页链接标题获取下一页

问题描述 投票:0回答:1

我想知道如何才能惯用地浏览位于

Link
标题的下一页。

现在我需要手动提取它:

    private fun getNextPageIfExists(link: String): String? =
        if (link.contains(""">;rel="next",""")) {
            link
                .substringBefore(""">;rel="next",""")
                .substringAfterLast("<")
        } else {
            null
        }

并使用提取的 URI 调用

RestClient

spring spring-boot kotlin spring-restclient
1个回答
0
投票

请记住,根据 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() }
© www.soinside.com 2019 - 2024. All rights reserved.