【问题标题】:type mismatch; found : scala.concurrent.Future[play.api.libs.ws.Response] required: play.api.libs.ws.Response类型不匹配;发现:scala.concurrent.Future[play.api.libs.ws.Response] 需要:play.api.libs.ws.Response
【发布时间】:2013-03-28 21:41:01
【问题描述】:

我正在尝试向 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
}

【问题讨论】:

    标签: scala playframework future playframework-2.1


    【解决方案1】:

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

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

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

    查看更多关于期货的信息here

    【讨论】:

    • 在 99% 的情况下,您不应该等待异步。与未来合作的所有必要工具都可以在框架中使用。
    • 感谢 Marius 和 Julien,你是对的,这会导致阻塞响应
    【解决方案2】:

    只需附加一个map

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

    【讨论】:

    • 感谢您的回答,您能解释一下为什么会这样吗?我的意思是,如何从未来中提取价值?
    【解决方案3】:

    假设您不想创建阻塞应用程序,您的方法也应该返回一个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
        }
      }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多