假设在我的 Controller 中有一组Sms对象。对于这些对象中的每一个,我想调用一个 Web 服务,然后对于所有成功的调用返回 sms 对象以进行查看。
控制器:
def inviteBySms() = Action {
implicit request => {
val smsSet = getSet()
Async {
smsSet.map(sms => callSmsService(sms).map(response => {
response.status match {
case 200 => {
// somehow add the sms object to a success set
}
case _ => {
// ignore
}
}
}))
// Return Ok() with the success Set[SMS]
}
}
}
控制器中的方法:
def postToService(sms: Sms) = {
val params = Map(Seq(current.configuration.getString("sms.service.user").getOrElse("")),
"pass" -> Seq(current.configuration.getString("sms.service.password").getOrElse("")),
"mobilephone" -> Seq(sms.number))
)
val futureResponse = WS.url(Play.current.configuration
.getString("sms.service.url").getOrElse(""))
.withHeaders("Content-Type" -> "application/x-www-form-urlencoded; charset=utf-8")
.post(params)
}