package com.scalawilliam.example.play import play.api.libs.ws._ /** * Play's Scala WS library is very very cool. Provides you with plenty niceties. * See more: https://www.playframework.com/documentation/2.3.x/ScalaWS * * Unfortunately it by default requires a Play application context. * But you do not necessarily always want that. * * William Narmontas, Scala Consultant, London. UK * https://www.scalawilliam.com/ */ object WSWithoutPlayApp extends App { class StandaloneWSAPI(wsClientConfig: WSClientConfig = DefaultWSClientConfig()) extends WSAPI with java.io.Closeable { import play.api.libs.ws.ning.{NingWSClient, NingAsyncHttpClientConfigBuilder} lazy val configuration = new NingAsyncHttpClientConfigBuilder(wsClientConfig).build() lazy val ningWsClient = new NingWSClient(configuration) override val client: WSClient = ningWsClient override def url(url: String): WSRequestHolder = client.url(url) def close(): Unit = { ningWsClient.close() } } val standaloneWSAPI = new StandaloneWSAPI() // Standard Play-style WSAPI val wsAPI: WSAPI = standaloneWSAPI def holder = { wsAPI.url("http://www.planetscala.com/atom.xml") .withHeaders("Accept" -> "application/xml") .withRequestTimeout(10000) } import scala.concurrent._ import scala.concurrent.duration._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Await def getPlanetScalaTitles: Future[Seq[String]] = { holder.get().map(_.xml \\ "title" map (_.text)) } println("Here are the first ten Planet Scala titles:") try { Await.result(getPlanetScalaTitles, 10.seconds) take 10 foreach println } finally { // required, else there'll be threads hanging around // you might not care to do this though. standaloneWSAPI.close() } }