![](/img/trans.png)
[英]Play framework, How to send HTTP GET/POST request to another site
[英]Play framework make http request from play server to “somesite.com” and send the response back to the browser
我正在使用scala中的Play框架开发一个应用程序。 我必须在我的应用程序中处理以下用例。
对于从浏览器到播放服务器的特定请求,Play服务器应向某个外部服务器发出http请求(例如:some:somesite.com),并将该请求的响应发送回Web浏览器。
我编写了以下代码,将请求发送到控制器中的外部设备。
val holder = WS.url("http://somesite.com")
val futureResponse = holder.get
现在我如何将收到的“somesite.com”的回复发回给浏览器?
WS中的Play文档中有一个示例,在控制器中使用 ; 我已根据您的情况调整了它:
def showSomeSiteContent = Action.async {
WS.url("http://somesite.com").get().map { response =>
Ok(response.body)
}
}
需要注意的关键是从get
调用中获取的Future
上map()
的惯用方法 - 一旦Future
成功完成,这个map
块中的代码将被执行。
Action.async
“包装器”告诉Play框架您将返回Future[Response]
并且您希望它执行必要的等待事情发生,如处理异步结果文档中所述 。
您可能还有兴趣动态返回状态和内容类型:
def showSomeSiteContent = Action.async {
WS.url("http://somesite.com").get().map { response =>
Status(response.status)(response.body).as(response.ahcResponse.getContentType)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.