如何使用Scala和Play Framework检查200 OK响应状态

时间:2016-01-27 21:54:49

标签: scala playframework httprequest httpresponse

我有一个以下的Actor类,负责使用POST向URL发送JSON消息。

import play.api.libs.ws._

class Worker extends Actor {
  val logger: Logger = Logger("superman")
  val supermanURL = "http://localhost:9000/superman/send"

  def receive = {

    case message: JsValue => {
      val transactionID = (message \ "transactionID").get
      println("Received JSON Object =>" + message)
      val responseFromSuperman = WS.url(supermanURL).withHeaders("Content-Type" -> "application/json").post(message)

      responseFromSuperman.map(
        result => {

          //TODO: Make sure to only log if response status is 200 OK

          logger.info("""Message="ACK received from Superman" for transactionID=""" + transactionID)}
      ).recover { case error: Throwable =>
        logger.error("""Message="NACK received from Superman" for transactionID=""" + transactionID) + " errorMessage:" + error.getLocalizedMessage()
      }
    }

  }

}

因此,如果您查看上面的TODO,我想添加一个200响应类型的检查。当前实现没有这样做,即使我手动发送BadRequest,它也会记录消息。我尝试检查返回的result.allHeaders

Map(Date -> Buffer(Wed, 27 Jan 2016 21:45:31 GMT), Content-Type -> Buffer(text/plain; charset=utf-8), Content-Length -> Buffer(7))

但没有关于回复状态的信息200 OK

2 个答案:

答案 0 :(得分:3)

简单地:

import play.api.http.Status

if(result.status == Status.OK) {
  // ...
}

答案 1 :(得分:0)

也许我在这里错过了一些东西,但你在回复中有“状态”。 所以你可以这样做:

WS.url(url).withHeaders("Content-Type" -> "application/json").post(message).map{
    case response if ( response.status == OK) => //DO SOMETHING?
}