我想使用播放2为外部api发出多个Web请求.每个Web请求将由page参数不同.我的代码是:
static WSRequestHolder urlPaging = WS
.url("http://my_api")
.setQueryParameter("apiKey", "api_key")
.setQueryParameter("pageSize", "5")
.setQueryParameter("format", "json");
public static Result insertProducts() {
int totalPages = 83;
Logger.info("total pages: " + totalPages);
for (int currentPage = 1; currentPage < totalPages; currentPage++) {
Logger.info("--current page:" + currentPage);
result(currentPage);
}
return ok();
}
public static AsyncResult result(int currentPage) {
return async(urlPaging
.setQueryParameter("page", String.valueOf(currentPage)).get()
.map(new Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
insertProductsFromPage(response);
return ok();
}
}));
}
Run Code Online (Sandbox Code Playgroud)
它适用于第1页,但为第2页提供了内部错误,所以我怀疑我没有result正确构建异步请求方法.请注意,我不需要这个真正的异步,因为我从管理员运行这个,我可以在那里等待所有这些请求被解析,但我还没有在播放2中找到同步方式.你能告诉我我做错了什么吗?
如果要同步进行外部WS调用,只需使用promise 的get()方法.
例如:
Promise<WS.Response> promise = urlPaging.setQueryParameter("page", String.valueOf(currentPage)).get();
WS.Response response = promise.get(); // wait for the result of the promise.
Run Code Online (Sandbox Code Playgroud)