Here is the implementation of your example.
Add the following importers:
import play.api.libs.ws.WS import play.api.mvc.BodyParsers.parse import scala.xml.XML
Add the following route:
case GET(Path("/testservice")) & QueryString(qs) => Action{ request => Async { val backendUrl = QueryString(qs,"target") map (_.get(0)) getOrElse("http://localhost:8080/api/token") val tokenData = QueryString(qs,"data") map (_.get(0)) getOrElse("<auth>john</auth>") WS.url(backendUrl).post(XML loadString tokenData).map { response => Ok(<html><h1>Posted to {backendUrl}</h1> <body> <div><p><b>Request body:</b></p>{tokenData}</div> <div><p><b>Response body:</b></p>{response.body}</div> </body></html>).as("text/html") } } }
All it does is forward a GET request to server serivce as a POST request. The internal service is specified in the request parameter as target , and the body of the POST request is specified in the request parameter as data (XML must be valid). As a bonus, the request is processed asynchronously (therefore, Async ). After receiving a response from the internal service, the external service responds to some basic HTML showing the response of the back-end service.
If you want to use the request body, I would suggest adding the following POST route, not GET (again, there must be valid XML in this tag):
case POST(Path("/testservice")) & QueryString(qs) => Action(parse.tolerantXml){ request => Async { val backendUrl = QueryString(qs,"target") map (_.get(0)) getOrElse("http://localhost:8080/api/token") WS.url(backendUrl).post(request.body).map { response => Ok(<html><h1>Posted to {backendUrl}</h1> <body> <div><p><b>Request body:</b></p>{request.body}</div> <div><p><b>Response body:</b></p>{response.body}</div> </body></html>).as("text/html") } } }
So, as you can see, for your HTTP gateway you can use Async and play.api.libs.ws.WS with Akka under the hood, working to provide asynchronous processing (without explicit Actors). Good luck with your Play2 / Akka2 project.
romusz
source share