类型失配;找到:scala.concurrent.Future[play.api.libs.ws.Response]必需:play.api.libs.ws.Response

类型失配;找到:scala.concurrent.Future[play.api.libs.ws.Response]必需:play.api.libs.ws.Response,scala,playframework,future,playframework-2.1,Scala,Playframework,Future,Playframework 2.1,我试图向Pusher api发出post请求,但返回正确类型时遇到问题,我发现类型不匹配;找到: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 = "/app

我试图向Pusher api发出post请求,但返回正确类型时遇到问题,我发现类型不匹配;找到: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
}
def触发器(通道:字符串、事件:字符串、消息:字符串):ws.Response={
val domain=“api.pusherapp.com”
val url=“/apps/”+appId+”/channels/“+channel+”/events”;
val body=消息
val参数=列表(
(“认证密钥”,密钥),
(“auth_timestamp”,(new Date().getTime()/1000)toInt),
(“auth_版本”、“1.0”),
(“名称”,事件),
(“body_md5”,md5(body))
).sortWith((a,b)=>a._1o._1+“=”+urlcoder.encode(o._2.toString)).mkString(“&”);
val signature=sha256(List(“POST”、url、params).mkString(“\n”)、secret.get);
val signatureEncoded=URLEncoder.encode(签名,“UTF-8”);
隐式val超时=超时(5秒)
WS.url(“http://“+domain+url+”?“+params+”&auth_signature=“+signatureEncoded”).post(正文)
}

只需添加一个
地图

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

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

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

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

查看有关未来的更多信息。

假设您不想创建阻止应用程序,您的方法还应该返回一个
Future[ws.Response]
。让您的未来冒泡到控制器,在控制器中使用
Async{…}
返回一个
AsyncResult
,并让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
    }
  }
}

我找不到异步{}在2.1 api中:我应该导入哪个库来使用Async?它与AsyncResult有什么不同?我目前导入这两个库,这两个库可能是相关的:
import scala.concurrent.\uimport play.api.libs.concurrent.Execution.Implicits.\u
谢谢这里。只需导入
play.api.mvc.
AsyncResult
是Result的一个子类,然后使用
Async{}创建
wrapper在您的控制器操作中。感谢您的回答,您能解释为什么这样做吗?我的意思是,如何从未来提取值?在99%的情况下,您不应该等待异步。所有与未来相关的必要工具都可以在框架中进行争议。谢谢Marius和Julien,您是对的,这会导致阻塞响应