简体   繁体   中英

Play framework make http request from play server to “somesite.com” and send the response back to the browser

I'm developing an application using Play framework in scala. I have to handle the below use case in my application.

For a particular request from the browser to the play server the Play server should make an http request to some external server (for Eg: somesite.com) and send the response from this request back to the web browser.

I have written the below code to send the request to external serever in the controller.

val holder = WS.url("http://somesite.com")
val futureResponse = holder.get

Now how do I send back the response recieved from "somesite.com" back to the browser?

There's an example in the Play documentation for WS , under Using in a controller ; I've adapted it to your scenario:

def showSomeSiteContent = Action.async {
  WS.url("http://somesite.com").get().map { response =>
    Ok(response.body)
  }
}

The key thing to note is the idiomatic use of map() on the Future that you get back from the get call - code inside this map block will be executed once the Future has completed successfully.

The Action.async "wrapper" tells the Play framework that you'll be returning a Future[Response] and that you want it to do the necessary waiting for things to happen, as explained in the Handling Asynchronous Results documentation .

You may also be interested in dynamically returning the status and content type:

def showSomeSiteContent = Action.async {
  WS.url("http://somesite.com").get().map { response =>
    Status(response.status)(response.body).as(response.ahcResponse.getContentType)
  }
}
  • Dynamic status could help if the URL/service you call fails to answer correctly.
  • Dynamic content type can be handy if your URL/service can return different content HTML/XML... depending on some dynamic parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM