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

StackOverflow https://stackoverflow.com/questions/21124104

Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top