代码之家  ›  专栏  ›  技术社区  ›  Oleg

设置内容类型标题

  •  0
  • Oleg  · 技术社区  · 7 年前

    Akka HTTP有问题。
    这个 Content-Type 标题默认值为 text/plain . 我正在试着设置 application/json 值如下:

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

    但这不管用。 内容类型 仍然是 文本/纯文本 .


    UPD
    我是 不是 正在读取客户端 内容类型 标题。我正试图从默认状态发送另一个 内容类型 来自服务器的头。


    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 负责人应:

    implicit def entity2ResponseMarshallable(entityF: Future[Entity]): ToResponseMarshallable =
      entityF map (_.toJson.toString())
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Astrid    7 年前

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

    如果你移除 .toString 从您的 entity2ResponseMarshallable 方法,所以简单来说

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

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

    这就是Akka HTTP想要处理 Content-Type 头-它根据最终使用的封送拆收器自动设置它。字符串,你以前有过,翻译成 text/plain .

    至于你最初的问题,我不相信改变 内容类型 此时可以手动收割台。根据 Akka documentation ,

    HTTP消息的内容类型被建模为httpEntity的ContentType字段。因此,内容类型头不会出现在消息的头序列中。此外,显式添加到请求或响应的头中的内容类型头实例将不会呈现到连接上,而是触发正在记录的警告!

    因此,为了手动设置内容类型,必须在 HttpEntity 实例与我最初链接的另一个问题相同-为了在路线级别上执行此操作,您必须重新定义 HTTPEntity公司 包含在您的 HttpResponse 在这个事实之后,我不确定这是可能的,在任何情况下这听起来都不是一个好主意。