我正在使用scala中的Play框架开发一个应用程序。我必须在我的应用程序中处理以下用例。
对于从浏览器到播放服务器的特定请求,Play服务器应向某个外部服务器发出http请求(例如:somesite.com),并将此请求的响应发送回Web浏览器。
我编写了以下代码,将请求发送到控制器中的外部设备。
val holder = WS.url("http://somesite.com")
val futureResponse = holder.get
现在如何将收到的来自“somesite.com”的回复发回给浏览器?
答案 0 :(得分:6)
Play documentation for WS中有在控制器中使用下的示例;我已根据您的情况进行了调整:
def showSomeSiteContent = Action.async {
WS.url("http://somesite.com").get().map { response =>
Ok(response.body)
}
}
需要注意的关键是map()
Future
上get
的惯用法,即map
调用中的Future
- 此Action.async
块内的代码将被执行Future[Response]
成功完成后。
{{1}}“包装器”告诉Play框架您将返回{{1}}并且您希望它做必要的等待事情发生,正如Handling Asynchronous Results documentation中所述。
答案 1 :(得分:2)
您可能还有兴趣动态返回状态和内容类型:
def showSomeSiteContent = Action.async {
WS.url("http://somesite.com").get().map { response =>
Status(response.status)(response.body).as(response.ahcResponse.getContentType)
}
}