score:13

Accepted answer

edit for play 2.5:

import akka.actor.actorsystem
import akka.stream.actormaterializer
import play.api.libs.ws._
import play.api.libs.ws.ahc.ahcwsclient

import scala.concurrent.future

object main {
  import scala.concurrent.executioncontext.implicits._

  def main(args: array[string]): unit = {
    implicit val system = actorsystem()
    implicit val materializer = actormaterializer()
    val wsclient = ahcwsclient()

    call(wsclient)
      .andthen { case _ => wsclient.close() }
      .andthen { case _ => system.terminate() }
  }

  def call(wsclient: wsclient): future[unit] = {
    wsclient.url("http://www.google.com").get().map { response =>
      val statustext: string = response.statustext
      println(s"got a response $statustext")
    }
  }
}

please see:

for more detailed examples of standalone wsclient usage. if you are migrating from earlier versions, see https://www.playframework.com/documentation/2.5.x/migration25#play-ws-upgrades-to-asynchttpclient-2

for play 2.4:

do not use raw asynchttpclientconfig.builder for https -- it does not configure a secure sslcontext with hostname validation.

you can create a new wsclient instance using the following code:

import play.api.libs.ws.ning._
import play.api.libs.ws._

val config = new ningasynchttpclientconfigbuilder(defaultwsclientconfig()).build()
val builder = new asynchttpclientconfig.builder(config)
val wsclient:wsclient = new ningwsclient(builder.build())

please note that this will start up threads which will not be closed until you close the client:

wsclient.underlying[ningwsclient].close()

and you may run into memory leaks if you don't close it.

score:4

a started playapplication contains a client instance, which ws.client simply points to it. since you won't start a play application, you have to create your own client, like this:

val client = {
  val builder = new com.ning.http.client.asynchttpclientconfig.builder()
  new play.api.libs.ws.ning.ningwsclient(builder.build())
}
client.url("http://example.com/").get()

have a look on my project for a similar usecase, i am using play-ws and play-json, without play itself.

score:8

play 2.4 makes it very easy to utilize ws in a standalone app.

the following gist provides a nice working example and the following blog post provides a nice explanation.

here are the highlights.

configure build.sbt

librarydependencies ++= seq(
  "com.typesafe.play" %% "play-ws" % "2.4.0-m2"
)

initialize the ws client

val config = new ningasynchttpclientconfigbuilder(defaultwsclientconfig()).build
val builder = new asynchttpclientconfig.builder(config)
val client = new ningwsclient(builder.build)

use ws

client.url("http://www.example.com").get

release ws resources

client.close()

Related Query

More Query from same tag