在scala的最新播放框架2.5.10中实现WS

时间:2017-04-08 21:17:34

标签: scala web-services playframework playframework-2.5

我想在scala中使用最新的play框架来查看GET api请求。我认为在Play 2.5+中改变了ws服务的用例。我正在使用以下代码。

class  ApiResult @Inject() (ws: WSClient)  {

  def getApiResult(param1: String, param2: String)= {

    var response = ws.url(s"ip-address/getApiResult/${param1}/${param2}").withRequestTimeout(5000.millis).get()
    var i = 0
    while(i < 2 && !response.isCompleted ){
     response = ws.url(s"ip-address/getSmsCredit/${param1}/${param2}").withRequestTimeout(5000.millis).get()
     i += 1
    }

    val result = response.onComplete {
     case Success(jsonOutput) => 
      val x= (jsonOutput.json \ "x").getOrElse(Json.toJson(-1)).as[Double]
      val y= (jsonOutput.json \ "y").getOrElse(Json.toJson(-1)).as[Double]
      val z= (jsonOutput.json \ "z").getOrElse(Json.toJson(-1)).as[Double]

      SomeCaseClass(x, y, z)
    case _ => 
     Logger.info("Error")
     SomeCaseClass(0.00, 0.00, 0.00)
   }
   result
 }
}

我想基本上返回SomeCaseClass,当我在其他一些函数中调用getApiResult时。另外,我如何在那里调用这个函数,因为这个函数使用了param WSClient

1 个答案:

答案 0 :(得分:0)

你的代码中有很多错误的东西,但我们假设你希望Future从这个方法返回,你应该做这样的事情:

def getApiResult(param1: String, param2: String): Future[SomeCaseClass] = {
   ws.url(s"ip-address/getApiResult/${param1}/${param2}")
     .withRequestTimeout(5000.millis).get()
     .flatMap(_ =>  //Will get here after the first request finished
        ws.url(s"ip-address/getSmsCredit/${param1}/${param2}")
        .withRequestTimeout(5000.millis).get()
        .map(_.body.validate[SomeCaseClass]
              .asOpt
              .getOrElse(SomeCaseClass(0.00, 0.00, 0.00)))
  )
}

您需要实现隐式阅读器:

object SomeCaseClass{
  implicit val reads: Reads[SomeCaseClass] = (
    (__ \ "x").read[Double] and
      (__ \ "y").read[Double] and
      (__ \ "z").read[Double]
    )(SomeCaseClass.apply _)
}

如果你想要实际的SomeCaseClass,你可以在getApiResult上做Await。