如何使用 Play Framework 2.2 进行同步 WS 调用 (Java)
How to make a synchronous WS call with Play Framework 2.2 (Java)
我正在寻找类似 this 但带有同步调用的示例。我的程序需要来自外部源的数据,应该等到响应 returns(或直到超时)。
Play WS 库用于异步请求,这很好!
使用它可以确保您的服务器不会被阻塞并等待一些响应(您的客户端可能会被阻塞,但这是另一个话题)。
只要有可能,您应该始终选择异步 WS 调用。请记住,您仍然可以访问 WS 调用的结果:
public static Promise<Result> index() {
final Promise<Result> resultPromise = WS.url(feedUrl).get().map(
new Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("Feed title:" + response.asJson().findPath("title"));
}
}
);
return resultPromise;
}
你只需要稍微不同地处理它——你提供一个映射函数——基本上你是在告诉 Play 在结果到达时如何处理它。然后你继续前进,让 Play 处理剩下的事情。不错,不是吗?
现在,如果您真的很想阻止,那么您将不得不使用另一个库来发出同步请求。 Apache HTTP 客户端有一个同步变体 - https://hc.apache.org/httpcomponents-client-ga/index.html
我也喜欢 Unirest 库 (http://unirest.io/java.html),它实际上位于 Apache HTTP 客户端之上,提供了更好更简洁的功能 API - 然后您可以执行以下操作:
Unirest.post("http://httpbin.org/post")
.queryString("name", "Mark")
.field("last", "Polo")
.asJson()
由于两者都是公开可用的,您可以将它们作为项目的依赖项 - 通过在 build.sbt
文件中说明。
你所能做的就是阻止调用,如果你愿意,等待直到得到超时响应。
WS.Response response = WS.url(url)
.setHeader("Authorization","BASIC base64str")
.setContentType("application/json")
.post(requestJsonNode)
.get(20000); //20 sec
JsonNode resNode = response.asJson();
在较新版本的游戏中,响应不再有 asJson()
方法。相反,杰克逊(或任何其他 json 映射器)必须应用于主体字符串:
final WSResponse r = ...;
Json.mapper().readValue(r, Type.class)
我正在寻找类似 this 但带有同步调用的示例。我的程序需要来自外部源的数据,应该等到响应 returns(或直到超时)。
Play WS 库用于异步请求,这很好!
使用它可以确保您的服务器不会被阻塞并等待一些响应(您的客户端可能会被阻塞,但这是另一个话题)。
只要有可能,您应该始终选择异步 WS 调用。请记住,您仍然可以访问 WS 调用的结果:
public static Promise<Result> index() {
final Promise<Result> resultPromise = WS.url(feedUrl).get().map(
new Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("Feed title:" + response.asJson().findPath("title"));
}
}
);
return resultPromise;
}
你只需要稍微不同地处理它——你提供一个映射函数——基本上你是在告诉 Play 在结果到达时如何处理它。然后你继续前进,让 Play 处理剩下的事情。不错,不是吗?
现在,如果您真的很想阻止,那么您将不得不使用另一个库来发出同步请求。 Apache HTTP 客户端有一个同步变体 - https://hc.apache.org/httpcomponents-client-ga/index.html
我也喜欢 Unirest 库 (http://unirest.io/java.html),它实际上位于 Apache HTTP 客户端之上,提供了更好更简洁的功能 API - 然后您可以执行以下操作:
Unirest.post("http://httpbin.org/post")
.queryString("name", "Mark")
.field("last", "Polo")
.asJson()
由于两者都是公开可用的,您可以将它们作为项目的依赖项 - 通过在 build.sbt
文件中说明。
你所能做的就是阻止调用,如果你愿意,等待直到得到超时响应。
WS.Response response = WS.url(url)
.setHeader("Authorization","BASIC base64str")
.setContentType("application/json")
.post(requestJsonNode)
.get(20000); //20 sec
JsonNode resNode = response.asJson();
在较新版本的游戏中,响应不再有 asJson()
方法。相反,杰克逊(或任何其他 json 映射器)必须应用于主体字符串:
final WSResponse r = ...;
Json.mapper().readValue(r, Type.class)