简体   繁体   中英

how to get response from post in javaws playframework 2.5

please help me, i want send json data to some API which use basic auth and i want catch respon from that API. this is my code:

@Inject
WSClient ws;
public Result testWS(){
JsonNode task = Json.newObject()
            .put("id", 123236)
            .put("name", "Task ws")
            .put("done", true);

WSRequest request = ws.url("http://localhost:9000/json/task").setAuth("user", "password", WSAuthScheme.BASIC).post(task);
return ok(request.tojson);

the question is how i get return from ws above and process it to json? because that code still error. i'm use playframework 2.5

.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM