如果您仍然想使用喷雾罐,那么您有两种选择,基于 HttpResponse 是一个案例类。第一种是传递具有显式内容类型的 List:
import spray.http.HttpHeaders._
import spray.http.ContentTypes._
def receive = {
case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
sender ! HttpResponse(entity = """{ "key": "value" }""", headers = List(`Content-Type`(`application/json`)))
}
或者,第二种方法是使用方法withHeaders
方法:
def receive = {
case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
val response: HttpResponse = HttpResponse(entity = """{ "key": "value" }""")
sender ! response.withHeaders(List(`Content-Type`(`application/json`)))
}
但是,就像jrudolph说的那样,使用喷雾路由要好得多,在这种情况下看起来会更好:
def receive = runRoute {
path("/something") {
get {
respondWithHeader(`Content-Type`(`application/json`)) {
complete("""{ "key": "value" }""")
}
}
}
}
但是喷雾使它变得更加容易并为您处理所有(非)编组:
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
def receive = runRoute {
(path("/something") & get) {
complete(Map("key" -> "value"))
}
}
在这种情况下,响应类型将由application/json
喷雾本身设置。
我的评论的完整示例:
class FullProfileServiceStack
extends HttpServiceActor
with ProfileServiceStack
with ... {
def actorRefFactory = context
def receive = runRoute(serviceRoutes)
}
object Launcher extends App {
import Settings.service._
implicit val system = ActorSystem("Profile-Service")
import system.log
log.info("Starting service actor")
val handler = system.actorOf(Props[FullProfileServiceStack], "ProfileActor")
log.info("Starting Http connection")
IO(Http) ! Http.Bind(handler, interface = host, port = port)
}