Reputation: 4018
I want to do something apparently simple: calling a webservice and saving the result in the database.
I'm inside an Akka Actor code and what I do is to call an object method:
object Service {
def run {
val response = WS.url("http://api.server.com/rest/")
.withAuth("test", "test", com.ning.http.client.Realm.AuthScheme.BASIC)
.get.value.get.get.body
}
}
How do I parse the body? I tried to print it on the console but I got NotSuchElement exception.
Any idea, thought? How do I parse arrays, attributes, elements of the XML ?
I'm in the play version 2.1.0
Upvotes: 1
Views: 4279
Reputation: 11244
Things have changed a bit since the previous version. Play 2.1.0 depends on the scala.concurrent
package instead of their own classes:
Promise
is now a Scala Future
Redeemable
is now a Scala Promise
I didn't have time to test it, but from the documentation I gathered it should be something like this:
import play.api.libs.ws.WS
import play.api.libs.concurrent.Execution.Implicits._
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.language.postfixOps
object WebserviceCallParseXML {
val responseFuture = WS.url("http://api.server.com/rest/")
.withAuth("test", "test", com.ning.http.client.Realm.AuthScheme.BASIC)
.get()
val resultFuture = responseFuture map { response =>
response.status match {
case 200 => Some(response.xml)
case _ => None
}
}
val result = Await.result(resultFuture, 5 seconds)
println(if (result.isDefined) result.get else "No result found" )
}
The documentation about Future.value
:
If the future is not completed the returned value will be None. If the future is completed the value will be Some(Success(t)) if it contains a valid result, or Some(Failure(error)) if it contains an exception.
Upvotes: 4