The Play WS library makes it possible to execute HTTP requests and process the response asynchronously. It provides an awesome API that is incredibly easy to use. (I’ve provided a few simple WS examples toward the end of this post.)
Prior to the release of Play 2.4 (the current 2.4 release is the M2 milestone release), it was possible to utilize the WS API in a standalone Play app, however you effectively had to bring in the entire Play Framework to use it. Ugh! This was due to a dependency on the Play core.
With the release of Play 2.4 (currently M2), this dependency no longer exists. It is now incredibly easy to utilize the WS library in any standalone Scala app.
The following steps describe how:
For the impatient, I’ve included working code in this gist on Github!
1. Add the following library dependency to build.sbt
libraryDependencies ++= Seq( "com.typesafe.play" %% "play-ws" % "2.4.0-M2" )
2. Initialize the WS client
val config = new NingAsyncHttpClientConfigBuilder(DefaultWSClientConfig()).build val builder = new AsyncHttpClientConfig.Builder(config) val client = new NingWSClient(builder.build)
Note, if using WS within the context of Play the above is not required
3. Make a request with WS. Below, are some simple examples
Be sure to provide an
client.url(url).post(Map("key" -> Seq("value")))
with query string
client.url(url). withQueryString("key" -> "value"). get
client.url(url). withHeaders("Content-Type" -> "application/json"). withQueryString("key" -> "value"). get
Note: If used within the context of play, replace
4. Close the client
Avoid leaks! Be sure to close the client and release threads.
Note: The above is not required if used within a Play app