1

我正在尝试在我的 Spring Boot 应用程序中使用 Traverson 来使用外部 HAL-api。这样做时,我在第一跳时遇到了异常org.apache.http.ProtocolException: Target host is not specified,即 Traverson 调用我的 baseUri 没有问题并且设置了目标主机,但似乎在第一跳时“忘记了”主机。

这是调用它的代码:

    override fun doStuff() {

        // baseUri gets injected by class and is of form "https://my.host.com"
        val startUri = UriComponentsBuilder.fromUriString(baseUri)
                // If dms is declared as first hop, Traverson would call baseUri before first hop which returns a html website and results in an error -> dms has to be part of Traverson baseUri
                .pathSegment("dms")
                .build()
                .toUri();

        val authHeader = HttpHeaders()
        // bearerToken gets injected by class and is not relevant for the problem
        authHeader.set(HttpHeaders.AUTHORIZATION, bearerToken)

        val restTemplate = RestTemplateBuilder()
                .rootUri(baseUri)
                .defaultHeader(HttpHeaders.AUTHORIZATION, bearerToken)
                .build()
        // httpRequestFactory gets injected by class and is used to configure SSL, should not matter for the problem
        restTemplate.requestFactory = httpRequestFactory

        val repoId: String = Traverson(startUri, MediaTypes.HAL_JSON)
                .setRestOperations(restTemplate)
                .follow("$._links.allrepos.href")
                .withHeaders(authHeader)
                .toObject("$.repositories[0].id")

        log.debug("Repo id is $repoId")
    }

这是 Traverson baseUri ( https://my.host.com/dms ) 的返回:

{
    _links: {
        allrepos: {
            href: "/dms/r"
        }
    }
}

执行此代码时,Traverson 获取我正在搜索的链接(“/dms/r”),但是当尝试跟踪它时,它执行对“/dms/r”而不是“https://my.host”的调用.com/dms/r”。

我错过了什么吗?

非常感谢您的每一点帮助!

编辑1: 可以使用以下代码实现我的目标。但是如果我不得不求助于这个选项,我会直接使用 restTemplate 而不发现 url,因为 Traverson 在这种情况下使用起来太不方便了。

        val allReposLink = Traverson(startUri, MediaTypes.HAL_JSON)
                .setRestOperations(restTemplate)
                .follow("$._links.allrepos.href")
                .withHeaders(headers)
                .asLink()
                .href

        val allReposUri = UriComponentsBuilder.fromUriString(baseUri)
                .pathSegment(allReposLink)
                .build()
                .toUri()
        val repoId = Traverson(allReposUri, MediaTypes.HAL_JSON)
                .setRestOperations(restTemplate)
                .follow("$.repositories[0].id")
                .withHeaders(headers)
                .asLink()
                .href

应该可以这样做:

// DOES NOT WORK
        val repoId: String = Traverson(startUri, MediaTypes.HAL_JSON)
                .setRestOperations(restTemplate)
                .follow("allrepos")
                .withHeaders(headers)
                .toObject("$.repositories[0].id")
4

0 回答 0