【问题标题】:Scala Play2 Error on Web Service callWeb服务调用上的Scala Play2错误
【发布时间】:2013-01-15 04:40:32
【问题描述】:

使用以下代码编译时出现错误。 我正在尝试调用 Web 服务。

def authenticate(username: String, password: String): String = {
    val request: Future[Response] = 
      WS.url(XXConstants.URL_GetTicket)
          .withTimeout(5000)
          .post( Map("username" -> Seq(username), "password" -> Seq(password) ) )            
      request map { response => 
        Ok(response.xml.text)
      } recover {
        case t: TimeoutException => 
          RequestTimeout(t.getMessage)
        case e =>
          ServiceUnavailable(e.getMessage)
      }

}

我看到以下编译器错误:

 type mismatch; found : scala.concurrent.Future[play.api.mvc.SimpleResult[String]] required: String

【问题讨论】:

    标签: web-services scala playframework playframework-2.0


    【解决方案1】:

    从您的authenticate 函数返回的值是val request = ...,其类型为Future[Response],但该函数需要String,正如编译器所说,这是一个类型不匹配错误。将函数的返回类型更改为Future[Response] 或在返回之前将request 转换为String 应该可以修复它。

    【讨论】:

      【解决方案2】:

      就像说布赖恩,当你的方法说你想返回一个String时,你目前正在返回一个Future[String]

      请求返回一个Future,因为它是一个异步调用。

      所以,你有两种选择:

      1. 更改您的方法定义以返回Future[String],并在另一个方法中管理这个未来(使用.map()

      2. 强制请求以同步方式立即获得此结果。这不是一个很好的交易,但有时它是最简单的解决方案。

        import scala.concurrent.Await
        import scala.concurrent.duration.Duration
        val response: String = Await.result(req, Duration.Inf)
        

      【讨论】:

        猜你喜欢
        • 2013-02-02
        • 2013-04-23
        • 2017-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多