0

我有一个服务定位器,它链接到外部 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格式。有可能实现这一目标吗?

*附注。响应仍然以正常Json格式出现

4

1 回答 1

2

只需按照Lagom 文档x-www-form-urlencoded中的说明添加序列化以用于您的FooRequest案例类

第一步:为和创建协商的序列化器和反序列化FooRequestx-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 对象生成消息序列化程序。

于 2020-07-02T10:19:15.620 回答