2016-06-01 76 views
2

过程阶跃响应我打电话一些REST API和处理JSON响应,读正式播放文档,我试试这个:播放2.5:从API

CompletionStage<JsonNode> token = ws.url("http://url.com") 
    .get() 
    .thenApply(response -> response.asJson()); 

但是,当我打印使用System.out.println(token)令牌,

我收到了此消息[email protected][Not completed]而不是JSON。

我仍然试图理解未来和承诺的概念,有什么我错过了吗?

在此先感谢

回答

2

如果你打破下来,你会发现如下:

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

通知的名字,我给了变量:eventualResponse。从.get()获得的内容不是来自HTTP调用的回复,而是承诺最终会有一个。

迈出下一步,我们有这样的:

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

再次,这是一个承诺eventualResponse完成并response(拉姆达参数)可用,asJson方法将在response调用。这也是异步发生的。

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

要处理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以获得简洁的介绍。

+0

谢谢!对于答案和参考,该维基百科文章确实给出了答案。 – Adakbar