akbarc
akbarc

Reputation: 109

Play 2.5: Process respones from API

I try to call some REST API and process the JSON response, reading the official Play doc, I try this one:

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

But when I print the token using System.out.println(token) ,

I got this message java.util.concurrent.CompletableFuture@4a5ece42[Not completed] instead of JSON.

I'm still trying to understand the concept of Future and Promise, is there anything that I missed?

Thanks in advance

Upvotes: 2

Views: 671

Answers (1)

Steve Chaloner
Steve Chaloner

Reputation: 8202

If you break this down, you'll find the following:

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

Notice the name I gave the variable: eventualResponse. What is obtained from .get() is not a reply from the HTTP call, but a promise that there will eventually be one.

Taking the next step, we have this:

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

Again, it's a promise that when eventualResponse is complete and response (the lambda parameter) is available, the asJson method will be invoked on response. This also happens asynchronously.

That means that what you're passing to System.out.println is not the JSON, but rather the promise of JSON. Accordingly, you're getting the toString signature of a CompletableFuture (which is an implementation of CompletionStage).

To process the JSON, keep the chain going:

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

NB There is a slight difference between a promise and a future - in this answer I've used the terms interchangably, but it's worth knowing the difference. Take a look at https://softwareengineering.stackexchange.com/a/207153 for a succinct take on this.

Upvotes: 2

Related Questions