17

I am using play2.5 with java 8. I am making POST request to server using

WSRequest request = ws.url("http://abababa .com");
WSRequest complexRequest = request.setHeader("X-API-Key", "xxxxxx")
            .setHeader("Content-Type", "application/x-www-form-urlencoded")
CompletionStage<WSResponse> responsePromise = complexRequest.post("grant_type=password"
            + "&username=xxxxx&password=yyyyy");
CompletionStage<JsonNode> jsonPromise = responsePromise.thenApply(WSResponse::asJson);

How do I print the final response of the response. I want to return part of the response to this function. Should the function which called this function also have different code compared to synchronous code?

raju
  • 4,788
  • 15
  • 64
  • 119

3 Answers3

25

jsonPromise.toCompletableFuture().get()

the8472
  • 40,999
  • 5
  • 70
  • 122
3
JsonNode jsonData = jsonPromise.toCompletableFuture().get()

I tried the code above but i get compiler error, to return JsonNode data, then i used

JsonNode jsonData = jsonPromise.toCompletableFuture().join()

and it works fine

brynetwork
  • 107
  • 1
  • 11
2

The problem is that all this code is being executed asynchronously. If you indeed want to return from the method with a result you will have to block until you get the result. Blocking is not good as it affects performance. Usually you want to return the CompletionStage as is and let the caller decide what to do with it. If however you have to absolutely return with a result a sample code is below.

WSRequest request = ws.url("http://abababa .com");
WSRequest complexRequest = request.setHeader("X-API-Key", "xxxxxx")
        .setHeader("Content-Type", "application/x-www-form-urlencoded")
CompletionStage<WSResponse> responsePromise =    complexRequest.post("grant_type=password"
        + "&username=xxxxx&password=yyyyy");
CompletionStage<JsonNode> jsonPromise = responsePromise.thenApply(WSResponse::asJson);
Object waitGuard = new Object();
AtomicReference<JsonNode> resultReference = new AtomicReference();
synchronized(waitGuard){
  jsonPromise.thenAccept( jsonNode -> {
  resultReference.set(jsonNode);
  waitGuard.notify();
  });
  waitGuard.wait();
}
return resultReference.get();
Kiran K
  • 703
  • 4
  • 11