如何使用Akka-http请求JSON或XML?

威廉

我离开了Akka世界几个月,显然我已经失去了魔力。我正在尝试编写一个基于Accept标头返回XML或JSON文档的Web服务。

但是,我无法让Marshallers工作(返回406,仅接受文本/纯文本)。这就是我所拥有的:

trait MyMarshallers extends DefaultJsonProtocol with SprayJsonSupport with ScalaXmlSupport {
  implicit def ec: ExecutionContext

  implicit val itemJsonFormat = jsonFormat3(MyPerson)


  def marshalCatalogItem(obj: MyPerson): NodeSeq =
    <MyPerson>
      <id>
        {obj.ID}
      </id>
      <name>
        {obj.Name}
      </name>
      <age>
        {obj.Age}
      </age>
    </MyPerson>

  def marshalCatalogItems(items: Iterable[MyPerson]): NodeSeq =
    <Team>
      {items.map(marshalCatalogItem)}
    </Team>

  implicit def catalogXmlFormat = Marshaller.opaque[Iterable[MyPerson], NodeSeq](marshalCatalogItems)

  implicit def catalogItemXmlFormat = Marshaller.opaque[MyPerson, NodeSeq](marshalCatalogItem)

  implicit val catalogMarshaller: ToResponseMarshaller[Iterable[MyPerson]] = Marshaller.oneOf(
    Marshaller.withFixedContentType(MediaTypes.`application/json`) { catalog ⇒
      HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`),
        catalog.map(i ⇒ MyPerson(i.ID, i.Name, i.Age))
          .toJson.compactPrint))
    }
    ,
    Marshaller.withOpenCharset(MediaTypes.`application/xml`) { (catalog, charset) ⇒
      HttpResponse(entity = HttpEntity.CloseDelimited(ContentType(MediaTypes.`application/xml`, HttpCharsets.`UTF-8`),
        Source.fromFuture(Marshal(catalog.map(i => MyPerson(i.ID, i.Name, i.Age)))
          .to[NodeSeq])
          .map(ns ⇒ ByteString(ns.toString()))
      )
      )
    }
  )
}

我的路线如下所示:

class MyService extends MyMarshallers {
  implicit val system = ActorSystem("myService")
  implicit val materializer = ActorMaterializer()
  implicit val ec: ExecutionContext = system.dispatcher

    ...
    def route = ...
        (get & path("teams")) {
              parameters('name.as[String]) { id =>
                complete {
                  getTeam(id)
                }

              }
      ...

}

如果我请求/,则得到纯文本,但是如果我请求application / xml或application / json,则得到406。

AKKA-HTTP如何确定它将接受的内容类型?我刚刚将所有内容更新为Akka 2.4.6。

威廉

对不起,我知道了。上面的代码有两个问题,其中一个解决了该问题:

  • 问题1-更改为在XML编组器中使用fromIterator而不是fromFuture
  • 问题2-我的getTeam()方法返回了Iterable。我将其更改为Seq。

现在一切正常。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章