【问题标题】:how to serve a html file correctly as correct content to a browser with akka-http?如何正确地将 html 文件作为正确的内容提供给带有 akka-http 的浏览器?
【发布时间】:2016-03-22 19:50:24
【问题描述】:

我正在查看 akka-http 文档,并在那里找到如何使用 HttpResponses 通过低级服务器 api 提供 html 内容。但是,我找不到任何关于如何提供 html 内容的好例子,应该在浏览器中正确表示。我发现并且可以工作的唯一事情是当它提供如下字符串内容时。我发现了一个例子:

imports akka.http.scaladsl.marshallers.xml.ScalaXmlSupport._

但我看不到 scaladsl 包含编组器(它包含编组)

import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.http.scaladsl.server.Directives._
import akka.actor.ActorSystem

object HttpAkka extends App{

   implicit val system = ActorSystem()
   implicit val materializer = ActorMaterializer()
   implicit val ec = system.dispatcher

   val route = get {
       pathEndOrSingleSlash {
           complete("<h1>Hello</h1>")
       }
   }

  Http().bindAndHandle(route, "localhost", 8080)

}

在这里Akka-http: Accept and Content-type handling找到一个相关问题

我没有完全理解该链接中的答案,但尝试了以下操作(我最终得到了这个工作..):

complete {
    HttpResponse(entity=HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say Hello</h1>"))
}

还有:

complete {
    respondWithHeader (RawHeader("Content-Type", "text/html(UFT-8"))
      "<h1> Say hello</h1>"
    } 

【问题讨论】:

  • 两者都不能像现在这样工作。对于 mustafas 建议,需要添加一个 xml 库,对于 kostyas suggestion I get a not found value error (if I use ContentTypes.text/html(UTF8)`,我得到一个类型不匹配。

标签: scala akka akka-http


【解决方案1】:

处理这个问题的最佳方法可能是使用ScalaXmlSupport 构建一个NodeSeq 编组器,它将正确地将内容类型设置为text/html。为此,您首先需要添加一个新的依赖项,因为默认情况下不包含 ScalaXmlSupport。假设你使用的是sbt,那么要添加的依赖如下:

"com.typesafe.akka" %% "akka-http-xml-experimental" % "2.4.2"

然后,您可以像这样设置一个路由来返回一个 Scala NodeSeq,当 akka 设置内容类型时,它将被标记为 text/html

implicit val system = ActorSystem()
import system.dispatcher
implicit val mater = ActorMaterializer()
implicit val htmlMarshaller = ScalaXmlSupport.nodeSeqMarshaller(MediaTypes.`text/html` )

val route = {
  (get & path("foo")){
    val resp = 
      <html>
        <body>
          <h1>This is a test</h1>
        </body>
      </html>

    complete(resp)
  }
}

Http().bindAndHandle(route, "localhost", 8080

获取text/htmltext/xml 的技巧是在ScalaXmlSupport 上使用nodeSeqMarshaller 方法,传入MediaTypes.text/html 作为媒体类型。如果您只是导入 ScalaXmlSupport._,那么默认的 marshaller 将在范围内将内容类型设置为 text/xml

【讨论】:

  • 如果从文件中读取 html 作为字符串,这是否也有效?例如 val resp = Source.fromFile("filePath").mkString?
  • @stian,如果您先采取额外步骤将从文件中读取的字符串转换为NodeSeq,它将起作用。
猜你喜欢
  • 1970-01-01
  • 2016-11-15
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
相关资源
最近更新 更多