【问题标题】:Set Content-Type header设置 Content-Type 标头
【发布时间】:2018-07-17 10:53:46
【问题描述】:

我对 akka-http 有疑问。
Content-Type 标头默认值为text/plain。我正在尝试像这样设置application/json 值:

val routes = 
  respondWithHeader(headers.`Content-Type`(ContentType(MediaTypes.`application/json`))) {
    // ...
    // all api routes
    // ...
  }

但这不起作用。 Content-Type 仍然是 text/plain


UPD
阅读客户Content-Type 标头。我正在尝试从服务器的默认 Content-Type 标头发送另一个。


UPD2
例如:

import JsonProtocol.entityFormat
//...
(get & path("api" / "entities")) {
  complete(getAllEntities)
}

getAllEntities 将来自DB 的实体列表返回为Future[Entity]Entity 只是一个模型:

case class Entity(foo: Int, bar: String)

EntityFormat 看起来像:

object JsonProtocol extends spray.json.DefaultJsonProtocol {
  implicit val entityFormat = jsonFormat2(Entity)
}

最后将 Future 转换为 ResponseMarshallable:

implicit def entity2ResponseMarshallable(entityF: Future[Entity]): ToResponseMarshallable =
  entityF map (_.toJson.toString())

【问题讨论】:

  • 你可以试试这个:respondWithHeader(RawHeader("Content-Type", "application/json"))
  • @tea-addict 同样的结果
  • @Astrid 我不这么认为。我有吨路线和吨吨complete 方法。我不想修改它们中的每一个。我想设置一次标题。
  • 如果您要返回 JSON 对象,最好查看其中一种方法的示例 - 通常 akka-http 会自动检测内容类型并将其设置为 application/json。 Content-Type 通常会得到特殊处理,并且看起来不能设置为标题 - 请参阅 doc.akka.io/docs/akka-http/current/common/…

标签: scala akka-http


【解决方案1】:

将 cmets 中的讨论与实际解决方案结合在一起:

如果您从您的 entity2ResponseMarshallable 方法中删除 .toString,那么只需拥有

implicit def entity2ResponseMarshallable(
      entityF: Future[Entity]): ToResponseMarshallable =
    entityF map (_.toJson)

您应该在服务器响应中获得正确的内容类型标头。

这就是 akka-http 想要处理 Content-Type 标头的方式 - 它会根据最终使用的编组器自动设置它。您之前拥有的字符串转换为text/plain

至于您最初的问题,我认为此时手动更改 Content-Type 标头是不可能的。根据Akka documentation

HTTP 消息的 Content-Type 被建模为 HttpEntity 的 contentType 字段。因此,Content-Type 标头不会出现在消息的标头序列中。此外,明确添加到请求或响应的标头的 Content-Type 标头实例不会被呈现到网络上,而是会触发记录警告!

因此,为了手动设置内容类型,您必须根据我最初链接的另一个问题在 HttpEntity 实例中覆盖它 - 为了在路由级别上执行此操作,您必须重新定义HttpEntity 包含在您的 HttpResponse 中,因为我不确定这是可能的,而且无论如何这听起来都不是一个好主意。

【讨论】:

    猜你喜欢
    • 2013-12-10
    • 2015-05-05
    • 2013-07-22
    • 2012-11-02
    • 2011-01-04
    • 1970-01-01
    • 2021-12-22
    • 2011-01-26
    • 2019-04-19
    相关资源
    最近更新 更多