我是框架新手,正在尝试集成微服务。我正在使用 WSClient 来调用 Web 服务。为了调用 POST Rest API,我传递了请求正文,其中包含一些必需参数和一些可选参数。我的问题是如何在这里传递可选参数?
我的代码示例是
def add = Action.async { implicit request =>
UserDataForm.bindFromRequest.fold(
profileForm => {
val response = profileForm.errorsAsJson
Future(BadRequest(response).as("application/json"))
},
userData => try {
ws.url("http://localhost:9000/" + "api/profile")
.post(
Map("userId" -> userData.userId, "firstName" -> userData.firstName, "lastName" -> userData.lastName, "country" -> userData.country, "address" -> userData.address)).map { response =>
OutputWithErrors(response.body, response.status)
}
} catch {
case e: Exception =>
Future(BadRequest(Message(false, e.getMessage).toJson.prettyPrint).as("application/json"))
})
}
所以这里address
是可选参数。
以及表单数据,即此处的userData
case class UserForm(userId: String, firstName: String, lastName: String, country: String, address: Option[String])
val UserDataForm = Form(
mapping(
"userId" -> nonEmptyText,
"firstName" -> nonEmptyText,
"lastName" -> nonEmptyText,
"country" -> nonEmptyText,
"address" -> optional(text)
)(UserForm.apply)(UserForm.unapply)
)
因此,在 ws.url(...)post(Map("userId"-> userData, ...))
附近调用休息服务 API 时,编译器提示 No 隐式找到参数证据$2:BodyWritable[Map[String, Serialized]]
最佳答案
这里的问题是您传递给post
的Map
。除一项外,所有项均为 (String, String)
,但最后一项为 (String, Option[String])
。
编译器现在必须弄清楚该集合的类型可能是什么,并沿着类型层次结构向上移动。它能找出的最佳类型是Map[String, Serialized]
。因为这是最窄的父类(super class)型 String 和 Option 实现。
这是帖子的定义:
def post[T: BodyWritable](body: T): Future[Response]
您可以看到 T 存在类型约束,这意味着您需要一个隐式转换器*来传递传递给 BodyWritable
的正文。您可以在 DefaultBodyWritables 中找到隐式 BodyWritables 。并且不存在 BodyWritable[Map[String, Serialized]]
。但有一个用于 Map[String, String]
你必须选择:
- 更改 map ,使其具有
Map[String, String]
类型,方法是通过getOrElse
为address
提供默认值或者如果地址为 None,则不将地址添加到 map 。 - 为 Map[String, Serialized] 编写一个 BodyWritable。 (这可能无法以令人满意的方式实现)
我建议你选择#1。
* 如果这不是此类隐式的正确术语,请纠正我。
关于java - 如何在 Play 框架中访问 Web 服务 API 时传递可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58321012/