![](/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.