我有一个服务定位器,它链接到外部URL。然后我想在我的实现中invoke
那个服务。
这是我的想法,在我的build.sbt中,我把我的服务的URL
lagomUnmanagedServices in ThisBuild := Map(
"Foo" -> "https://www.xxxxxx.com"
)
然后,我有一个确切名称为的服务
trait FooService extends Service {
override final def descriptor: Descriptor = {
import Service._
named("Foo")
.withCalls(
restCall(Method.POST, "/PostUrl", fooServiceCall _)
.withRequestSerializer(???)
)
.withAutoAcl(true)
}
def fooServiceCall(): ServiceCall[FooRequest, FooResponse]
然后我可以通过调用来调用这个服务/api
fooService.fooServiceCall.invoke()
但问题是,我发送的请求应该格式化为x-www-form-urlencoded
,而不是普通的Json
格式。有可能做到这一点吗?
*PS。响应仍然是正常的Json
格式
只需要添加序列化,即可将x-www-form-urlencoded
用于FooRequest
案例类,遵循Lagom文档中的说明
第一步:为FooRequest
和x-www-form-urlencoded
创建协商序列化程序和反序列化程序
class FooUrlEncodedSerializer extends NegotiatedSerializer[FooRequest, ByteString] {
override val protocol = MessageProtocol(Some("application/x-www-form-urlencoded"))
// Convert your FooRequest in a ByteString following the format of urlencoded protocol
// "field1=value1;field2=value2;..."
def serialize(fooRequest: FooRequest) =
ByteString.fromString(...)
}
class FooUrlEncodedDeserializer extends NegotiatedDeserializer[FooRequest, ByteString] {
// Convert a ByteString urlencoded in a FooRequest object
def deserialize(bytes: ByteString): FooRequest = {...}
}
第二步:创建要在调用中使用的MessageSerializer
class FooRequestFormUrlEncodedSerializer extends StrictMessageSerializer[FooRequest] {
override def serializerForRequest: NegotiatedSerializer[FooRequest, ByteString] = new FooUrlEncodedSerializer
override def deserializer(protocol: MessageProtocol): MessageSerializer.NegotiatedDeserializer[FooRequest, ByteString] = new FooUrlEncodedDeserializer
override def serializerForResponse(acceptedMessageProtocols: Seq[MessageProtocol]): NegotiatedSerializer[FooRequest, ByteString] = new FooUrlEncodedSerializer
}
最后一步:将序列化程序添加到您的服务描述符:
trait FooService extends Service {
override final def descriptor: Descriptor = {
import Service._
named("Foo")
.withCalls(
restCall(Method.POST, "/PostUrl", fooServiceCall _)
.withRequestSerializer(new FooRequestFormUrlEncodedSerializer)
)
.withAutoAcl(true)
}
def fooServiceCall(): ServiceCall[FooRequest, FooResponse]
由于您希望以Json的身份接收响应,因此不需要为FooResponse对象生成消息序列化程序。