2016-01-27 85 views
0

我有一個以下Actor類負責使用POST向URL發送JSON消息。如何使用Scala和Play Framework檢查200 OK響應狀態

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 OK。目前的實施沒有這樣做,並且即使我手動發送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

回答

3

簡單的信息:

import play.api.http.Status 

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

我試過了,它說「無法解析符號確定」。我也有'進口play.api.mvc.Result._'在那裏,但沒有爲我工作 – summerNight

+0

您需要:''import play.api.http.Status'' –

+0

真棒,謝謝! – summerNight

0

也許我失去了一些東西,但你必須對「身份」響應。 所以你可以這樣做:

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

解決方案中的「響應」是什麼? – summerNight

+0

發佈(消息)的結果,你可以嘗試。 – Tomer

相關問題