WS.url发布在Scala中

时间:2014-04-11 09:02:50

标签: web-services scala post playframework-2.0

我正在使用Play框架调用Web服务。功能是:

 def addCustomerFunction = Action.async { implicit request =>
   val (firstName, lastName, accountBalance, dateOfBirth) = addCustomerForm.bindFromRequest.get
   WS.url("http://localhost:8080/customer").post(Map("firstName" -> Seq(firstName), "lastName" ->  Seq(lastName),
  "accountBalance" -> Seq(accountBalance), "birthday" -> Seq(dateOfBirth))).map { response =>
  Ok(response.body)
}

}

我得到的错误是:

Cannot write an instance of scala.collection.immutable.Map[String,Seq[Any]] to HTTP 
response. Try to define a Writeable[scala.collection.immutable.Map[String,Seq[Any]]] 

我不明白我做错了什么?有什么想法吗?

3 个答案:

答案 0 :(得分:1)

以下代码有效:

def addCustomerFunction = Action.async { implicit request =>
val (firstName, lastName, accountBalance, dateOfBirth) = addCustomerForm.bindFromRequest.get
val data = Json.obj(
  "firstName" -> firstName,
  "lastName" -> lastName,
  "accountBalance" -> accountBalance,
  "birthday" -> dateOfBirth
)
WS.url("http://localhost:8080/customer").post(data).map { response =>
  Ok(response.body)
}
}

谢谢年龄!

答案 1 :(得分:1)

.post()需要Map[String,Seq[String]],但您需要Map[String,Seq[Any]]。您传递到Map的所有值都应为string。您可能传递了Int作为参数。将其转换为toString,错误将消失。

WS.url("http://localhost:8080/customer")
  .post(Map(
    "firstName" -> Seq(firstName), 
    "lastName" ->  Seq(lastName),
    "accountBalance" -> Seq(accountBalance.toString), 
    "birthday" -> Seq(dateOfBirth.toString)))
  .map { response => 
    Ok(response.body)
  }

答案 2 :(得分:0)

正如您在输出中所解释的那样,Map不是Writeable的实例。您应该发送带有帖子的可写入内容。您必须使用Writeable转换数据,例如将其转换为JSON并使用Writeable伴随对象。请注意,它可能不是外部Web服务的有效输入,因此JSON可能无法正常工作,但这个想法就在这里。

您可以在这里查看更多详情: How do I set params for WS.post() in play 2.1 Java

答案是Java,而不是Scala。您可以尝试在Scala中使用withQueryString。