类型不匹配;发现:scala.concurrent.Future [play.api.libs.ws.Response]必需:play.api.libs.ws.Response

时间:2013-03-28 21:41:01

标签: scala playframework future playframework-2.1

我正在尝试向Pusher api发布帖子请求,但我无法返回正确的类型,我的类型不匹配;发现:scala.concurrent.Future [play.api.libs.ws.Response]必需:play.api.libs.ws.Response

def trigger(channel:String, event:String, message:String): ws.Response = {
val domain = "api.pusherapp.com"
val url = "/apps/"+appId+"/channels/"+channel+"/events";
val body = message

val params = List( 
  ("auth_key", key),
  ("auth_timestamp", (new Date().getTime()/1000) toInt ),
  ("auth_version", "1.0"),
  ("name", event),
  ("body_md5", md5(body))
).sortWith((a,b) => a._1 < b._1 ).map( o => o._1+"="+URLEncoder.encode(o._2.toString)).mkString("&");

    val signature = sha256(List("POST", url, params).mkString("\n"), secret.get); 
    val signatureEncoded = URLEncoder.encode(signature, "UTF-8");
    implicit val timeout = Timeout(5 seconds)
    WS.url("http://"+domain+url+"?"+params+"&auth_signature="+signatureEncoded).post(body
}

3 个答案:

答案 0 :(得分:4)

您使用post发出的请求是异步的。该调用立即返回,但不返回Response对象。相反,它返回一个Future[Response]对象,一旦http请求异步完成,它将包含Response对象。

如果要在请求完成之前阻止执行,请执行以下操作:

val f = Ws.url(...).post(...)
Await.result(f)

详细了解期货here

答案 1 :(得分:3)

只需附加一个map

WS.url("http://"+domain+url+"?"+params+"&auth_signature="+signatureEncoded).post(body).map(_)

答案 2 :(得分:3)

假设您不想创建阻止应用,您的方法也应返回Future[ws.Response]。让你的期货冒泡到控制器,你使用AsyncResult返回Async { ... }并让Play处理其余部分。

控制器

def webServiceResult = Action { implicit request =>
  Async {
    // ... your logic
    trigger(channel, event, message).map { response =>
      // Do something with the response, e.g. convert to Json
    }
  }
}
相关问题