设置 Content-Type header

Set Content-Type header

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

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

但这行不通。 Content-Type 仍然是 text/plain


UPD
不是阅读客户Content-Typeheader。我正在尝试从服务器默认 Content-Type header 发送另一个


UPD2
例如:

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

getAllEntities returns 来自 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())

将评论中的讨论与实际解决方案结合起来:

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

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

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

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

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

The Content-Type of an HTTP message is modeled as the contentType field of the HttpEntity. The Content-Type header therefore doesn’t appear in the headers sequence of a message. Also, a Content-Type header instance that is explicitly added to the headers of a request or response will not be rendered onto the wire and trigger a warning being logged instead!

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