Bourne
Bourne

Reputation: 1927

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?

Upvotes: 3

Views: 7394

Answers (2)

Patrick Refondini
Patrick Refondini

Reputation: 685

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.

Upvotes: 4

millhouse
millhouse

Reputation: 10007

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.

Upvotes: 6

Related Questions