.post(task)
results in a CompletionStage<WSResponse>
, so you can't just call toJson
on it. You have to get the eventual response from the completion stage (think of it as a promise). Note the change to the method signature too.
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.fasterxml.jackson.databind.JsonNode;
import play.libs.Json;
import play.libs.ws.WSAuthScheme;
import play.libs.ws.WSClient;
import play.libs.ws.WSResponse;
import play.mvc.Controller;
import play.mvc.Result;
import scala.concurrent.ExecutionContextExecutor;
@Singleton
public class FooController extends Controller {
private final WSClient ws;
private final ExecutionContextExecutor exec;
@Inject
public FooController(final ExecutionContextExecutor exec,
final WSClient ws) {
this.exec = exec;
this.ws = ws;
}
public CompletionStage<Result> index() {
final JsonNode task = Json.newObject()
.put("id", 123236)
.put("name", "Task ws")
.put("done", true);
final CompletionStage<WSResponse> eventualResponse = ws.url("http://localhost:9000/json/task")
.setAuth("user",
"password",
WSAuthScheme.BASIC)
.post(task);
return eventualResponse.thenApplyAsync(response -> ok(response.asJson()),
exec);
}
}
Check the documentation for more details of working with asynchronous calls to web services.