9

スプレーがそれを行うことは理解していますが、それでもヘッダーでオーバーライドしたいのですが、応答でヘッダーをオーバーライドするにはどうすればよいですか?

私の応答は次のようになります。

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
4

4 に答える 4

14

それでもスプレー缶を使用したい場合は、HttpResponse がケース クラスであることから、2 つのオプションがあります。1 つ目は、明示的なコンテンツ タイプを持つ 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`)))
  }

または、2 番目の方法は、メソッド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)
}
于 2013-10-16T06:52:58.283 に答える
3

entityパラメーターHttpResponseは実際には型HttpEntityであり、文字列は暗黙的に のインスタンスにのみ変換されますHttpEntity。他のコンストラクターのいずれかを使用してコンテンツ タイプを指定できます。夜間バージョンのスプレーで可能なコンストラクターのソースを参照してください。

また、スプレー ルーティングを使用する場合は、マーシャリング/アンマーシャリングをインフラストラクチャに任せることができます。

于 2013-10-16T06:29:05.897 に答える
1

4lex1v の回答に追加するには、GeoTrellis サイトに、build.sbt. GeoTrellis の部分も、このスタック オーバーフローの質問のために簡単に削除できます。

http://geotrellis.io/tutorials/webservice/spray/

于 2015-04-03T23:27:29.960 に答える