播放 2.5:处理来自 API 的响应
Play 2.5: Process respones from API
我尝试调用一些 REST API 并处理 JSON 响应,阅读官方 Play 文档,我尝试这个:
CompletionStage<JsonNode> token = ws.url("http://url.com")
.get()
.thenApply(response -> response.asJson());
但是当我使用 System.out.println(token)
打印令牌时,
我收到这条消息 java.util.concurrent.CompletableFuture@4a5ece42[Not completed]
而不是 JSON。
我还在努力理解 Future 和 Promise 的概念,有什么我错过的吗?
提前致谢
如果将其分解,您会发现以下内容:
CompletionStage<WSResponse> eventualResponse = ws.url("http://url.com").get()
注意我给变量起的名字:eventualResponse
。从 .get()
获得的不是来自 HTTP 调用的回复,而是 承诺 最终会有一个。
下一步,我们有这个:
CompletionStage<JsonNode> eventualJson = eventualResponse.thenApply(response -> response.asJson());
同样,承诺,当 eventualResponse
完成并且 response
(lambda 参数)可用时,asJson
方法将在 response
上调用。这也是异步发生的。
这意味着您传递给 System.out.println
的不是 JSON,而是 JSON 的承诺。因此,您将获得 CompletableFuture
的 toString
签名(这是 CompletionStage
的实现)。
要处理 JSON,请继续链:
ws.url("http://url.com")
.get()
.thenApply(response -> response.asJson())
.thenApply(json -> do something with the JSON)
. and so on
NB promise 和 future 之间存在细微差别 - 在这个答案中,我交替使用了这两个术语,但值得了解它们之间的区别。请查看 https://softwareengineering.stackexchange.com/a/207153 以获得对此的简要介绍。
我尝试调用一些 REST API 并处理 JSON 响应,阅读官方 Play 文档,我尝试这个:
CompletionStage<JsonNode> token = ws.url("http://url.com")
.get()
.thenApply(response -> response.asJson());
但是当我使用 System.out.println(token)
打印令牌时,
我收到这条消息 java.util.concurrent.CompletableFuture@4a5ece42[Not completed]
而不是 JSON。
我还在努力理解 Future 和 Promise 的概念,有什么我错过的吗?
提前致谢
如果将其分解,您会发现以下内容:
CompletionStage<WSResponse> eventualResponse = ws.url("http://url.com").get()
注意我给变量起的名字:eventualResponse
。从 .get()
获得的不是来自 HTTP 调用的回复,而是 承诺 最终会有一个。
下一步,我们有这个:
CompletionStage<JsonNode> eventualJson = eventualResponse.thenApply(response -> response.asJson());
同样,承诺,当 eventualResponse
完成并且 response
(lambda 参数)可用时,asJson
方法将在 response
上调用。这也是异步发生的。
这意味着您传递给 System.out.println
的不是 JSON,而是 JSON 的承诺。因此,您将获得 CompletableFuture
的 toString
签名(这是 CompletionStage
的实现)。
要处理 JSON,请继续链:
ws.url("http://url.com")
.get()
.thenApply(response -> response.asJson())
.thenApply(json -> do something with the JSON)
. and so on
NB promise 和 future 之间存在细微差别 - 在这个答案中,我交替使用了这两个术语,但值得了解它们之间的区别。请查看 https://softwareengineering.stackexchange.com/a/207153 以获得对此的简要介绍。