10

我的路线如下:

val route = {
    logRequestResult("user-service") {
      pathPrefix("user") {
        get {
          respondWithHeader(RawHeader("Content-Type", "application/json")) {
            parameters("firstName".?, "lastName".?).as(Name) { name =>
              findUserByName(name) match {
                case Left(users) => complete(users)
                case Right(error) => complete(error)
              }
            }
          }
        } ~
          (put & entity(as[User])) { user =>
            complete(Created -> s"Hello ${user.firstName} ${user.lastName}")
          } ~
          (post & entity(as[User])) { user =>
            complete(s"Hello ${user.firstName} ${user.lastName}")
          } ~
          (delete & path(Segment)) { userId =>
            complete(s"Hello $userId")
          }
      }
    }
  }

我的响应的内容类型应该始终是application/json我为get请求设置的。但是,我在测试中得到的是text/plain. 如何在响应中正确设置内容类型?

顺便说一句,akka-http 文档是我见过的最没有价值的垃圾之一。几乎每个示例代码的链接都被破坏了,它们的解释只是说明了显而易见的。Javadoc 没有代码示例,我在 Github 上找不到他们的代码库,因此从他们的单元测试中学习也是不可能的。

4

1 回答 1

9

我发现这篇文章 “在 spray/akka-http 中,一些标头被特殊处理”。显然,内容类型是其中之一,因此不能像我上面的代码那样设置。必须改为创建HttpEntity具有所需内容类型和响应正文的内容。有了这些知识,当我get如下更改指令时,它就起作用了。

import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.model.MediaTypes.`application/json`

get {
  parameters("firstName".?, "lastName".?).as(Name) { name =>
    findUserByName(name) match {
      case Left(users) => complete(users)
      case Right(error) => complete(error._1, HttpEntity(`application/json`, error._2))
    }
  }
}
于 2015-09-07T04:39:40.183 回答