2

使用以下代码编译时出现错误。我正在尝试调用 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
4

2 回答 2

2

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

于 2013-01-08T06:25:05.490 回答
2

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

该请求返回 aFuture因为它是一个异步调用。

因此,您有两种选择:

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

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

    import scala.concurrent.Await
    import scala.concurrent.duration.Duration
    val response: String = Await.result(req, Duration.Inf)
    
于 2013-01-08T08:25:01.587 回答