【问题标题】:Play 2.5: Process respones from API播放 2.5:处理来自 API 的响应
【发布时间】:2016-06-03 13:52:00
【问题描述】:

我尝试调用一些 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 的概念,有什么我遗漏的吗?

提前致谢

【问题讨论】:

    标签: java playframework-2.5


    【解决方案1】:

    如果你把它分解,你会发现以下内容:

    CompletionStage<WSResponse> eventualResponse = ws.url("http://url.com").get()
    

    注意我给变量取的名字:eventualResponse。从.get()得到的不是HTTP调用的回复,而是一个promise最终会有的。

    下一步,我们有这个:

    CompletionStage<JsonNode> eventualJson = eventualResponse.thenApply(response -> response.asJson());
    

    再次,承诺eventualResponse 完成并且response(lambda 参数)可用时,将在response 上调用asJson 方法。这也是异步发生的。

    这意味着您传递给System.out.println 的不是JSON,而是JSON 的承诺。因此,您将获得CompletableFuturetoString 签名(这是CompletionStage 的实现)。

    要处理 JSON,请保持链继续运行:

    ws.url("http://url.com")
      .get()
      .thenApply(response -> response.asJson())
      .thenApply(json -> do something with the JSON)
      . and so on
    

    NB 承诺和未来之间存在细微差别 - 在这个答案中,我可以互换使用这些术语,但值得了解它们的区别。看一下https://softwareengineering.stackexchange.com/a/207153 的简要介绍。

    【讨论】:

    • 谢谢!对于答案和参考,那篇维基百科文章确实给出了答案。
    猜你喜欢
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2021-03-26
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多