scala 我如何指定喷雾 Content-Type 响应标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19396187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i specify spray Content-Type response header?
提问by Jas
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
回答by 4lex1v
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:
如果你还想使用spray can,那么你有两个选择,基于HttpResponse是一个case类。第一种是传递具有显式内容类型的 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`)))
}
Or, the second way, is to use a method withHeadersmethod:
或者,第二种方法是使用方法withHeaders方法:
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 jrudolphsaid, it's much better to use spray routing, in this case it would look better:
但是,就像jrudolph所说的,使用喷雾路由要好得多,在这种情况下它看起来会更好:
def receive = runRoute {
path("/something") {
get {
respondWithHeader(`Content-Type`(`application/json`)) {
complete("""{ "key": "value" }""")
}
}
}
}
But spray makes it even easier and handles all (un)marshalling for you:
但是spray 使它更容易,并为您处理所有(取消)编组:
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
def receive = runRoute {
(path("/something") & get) {
complete(Map("key" -> "value"))
}
}
In this case reponse type will be set to application/jsonby the spray itself.
在这种情况下,响应类型将由application/json喷雾本身设置。
Complete example for my comment:
我的评论的完整示例:
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)
}
回答by jrudolph
The entityparameter of HttpResponseis actually of type HttpEntityand your string is only implicitly converted into an instance of HttpEntity. You can use one of the other constructors to specify a content-type. See the sourcefor the possible constructors in the nightly version of spray.
entityof的参数HttpResponse实际上是类型HttpEntity,您的字符串只是隐式转换为HttpEntity. 您可以使用其他构造函数之一来指定内容类型。请参阅每晚版本的 Spray 中可能的构造函数的来源。
Also if you use spray-routing, you can leave marshalling/unmarshalling to the infrastructure.
此外,如果您使用喷雾路由,您可以将编组/解组留给基础设施。
回答by Jean
In recent version of Spray (1.2.4 / 1.3.4), you may want to use respondWithMediaType. Here is the sample from the documentation:
在最新版本的 Spray (1.2.4 / 1.3.4) 中,您可能需要使用respondWithMediaType. 这是文档中的示例:
val route =
path("foo") {
respondWithMediaType(`application/json`) {
complete("[]") // marshalled to `text/plain` here
}
}
Note that while this overrides the HTTP header value, it will not override the marshaller used for serializing your content to the wire.
请注意,虽然这会覆盖 HTTP 标头值,但它不会覆盖用于将您的内容序列化到线路的编组器。
Therefore using a recent spray with spray routing, the original code would look like :
因此,使用最近的带有喷射路由的喷射,原始代码如下所示:
def receive = runRoute {
path("/something") {
get {
respondWithMediaType(`application/json`) {
complete("""{ "key": "value" }""")
}
}
}
}
回答by Ram Rajamony
To add to 4lex1v's answer, there is a very nice, short, simple, working (as of 4/15, scala 2.11.5) tutorial on the GeoTrellis site, including a build.sbt. The GeoTrellis pieces are also straightforward to eliminate for the purposes of this stack overflow question.
要添加到 4lex1v 的答案中,GeoTrellis 站点上有一个非常好的、简短的、简单的工作(截至 4/15,scala 2.11.5)教程,包括build.sbt. 为了解决这个堆栈溢出问题,GeoTrellis 部分也很容易消除。

