请帮助我,我想将json数据发送到一些使用基本身份验证的API,我希望从该API中获取响应。这是我的代码:
@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);
问题是我如何从上面的ws返回并将其处理为json?因为该代码仍然是错误的。我正在使用playframework 2.5
答案 0 :(得分:0)
.post(task)
会生成CompletionStage<WSResponse>
,因此您不能只在其上调用toJson
。您必须从完成阶段获得最终响应(将其视为承诺)。请注意方法签名的更改。
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);
}
}
检查documentation以获取有关使用Web服务异步调用的更多详细信息。