user1877249
user1877249

Reputation: 3

How to get result from WS call in play framework/scala?

I have a big trouble with getting value from WS.url call.

val x =WS.url("https://www.google.com/recaptcha/api/siteverify?
secret=XX&response="+captcha).get().map {
response =>response.body}

When i try

Console.println("X: "+x)

I don't have expected value but:

X: scala.concurrent.impl.Promise$DefaultPromise@e17c7c

BUT, when i try to print value println(response.body) inside map function it works fine.

I also tried playframework tutorial but the same results.

So, how can I assign result of GET call into some variable?

Upvotes: 0

Views: 1381

Answers (1)

Akos Krivachy
Akos Krivachy

Reputation: 4966

Please don't assemble your own query string, use the withQueryString method.

There are two solutions to your problem: blocking and non-blocking. Blocking will mean that your request's thread will idle until the HTTP call completes. Non-blocking is preferred and you can provide Play with a Future to complete the request with. All you have to do is instead of Action use Action.async in your controller.

val captchaResponse: Future[String] =
  WS.url("https://www.google.com/recaptcha/api/siteverify")
    .withQueryString("secret" -> "XX", "response" -> "captcha")
    .get()
    .map(_.body)

// Non-blocking solution:
captchaResponse.map {
  body =>
    Console.println("X: " + body)
    Ok(views.html.page(body.toBoolean))
}

// Blocking solution:
import scala.concurrent.duration._
val x = Await.result(captchaResponse, 3.seconds)
Console.println(x)

Upvotes: 2

Related Questions