问题描述
我知道Spray可以为我做到这一点,但是我仍然想用标题覆盖它,如何在响应中覆盖标题?
I understand that spray does that for me, but I still want to override it with my header, how can I override the header in the response?
我的响应看起来像这样:
My response looks like this:
case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
sender ! HttpResponse(entity = """{ "key": "value" }""" // here i want to specify also response header i would like to explicitly set it and not get it implicitly
推荐答案
如果您仍然想使用Spray can,那么您有两个选择,基于HttpResponse是第一个是传递具有显式内容类型的List:
If you still want to use spray can, then you have two options, based on that HttpResponse is a case class. The first is to pass a List with an explicit content type:
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
方法:
Or, the second way, is to use a method withHeaders
method:
def receive = {
case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
val response: HttpResponse = HttpResponse(entity = """{ "key": "value" }""")
sender ! response.withHeaders(List(`Content-Type`(`application/json`)))
}
但是,仍然像所说,使用喷涂工艺要好得多,在这种情况下看起来会更好:
But still, like jrudolph said, it's much better to use spray routing, in this case it would look better:
def receive = runRoute {
path("/something") {
get {
respondWithHeader(`Content-Type`(`application/json`)) {
complete("""{ "key": "value" }""")
}
}
}
}
但是喷雾使操作更轻松,并能处理所有(un )为您编组:
But spray makes it even easier and handles all (un)marshalling for you:
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
def receive = runRoute {
(path("/something") & get) {
complete(Map("key" -> "value"))
}
}
在这种情况下,响应类型将设置为 application / json
In this case reponse type will be set to application/json
by the spray itself.
我的评论的完整示例:
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)
}
这篇关于如何指定喷雾Content-Type响应标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!