首页 > 解决方案 > Scala 和 Akka HTTP:如何将实体内容作为字符串获取

问题描述

我对 Akka HTTP 很陌生,所以请事先接受我对这个非常基本的问题的歉意。

在下面的代码中,我想从 HTTP 请求中检索实体(实体将是纯文本),从实体中获取文本,并将其作为响应返回。

  implicit val system = ActorSystem("ActorSystem")
  implicit val materializer = ActorMaterializer
  import system.dispatcher

  val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].map {
    case HttpRequest(HttpMethods.POST, Uri.Path("/api"), _, entity, _) =>
      val entityAsText = ... // <- get entity content as text

      HttpResponse(
        StatusCodes.OK,
        entity = HttpEntity(
          ContentTypes.`text/plain(UTF-8)`,
          entityAsText
        )
      )
  }

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

如何获取实体的字符串内容?

提前谢谢了!

标签: scalahttprequesthttpresponseakka-streamakka-http

解决方案


一种方法是调用toStrictRequestEntity将实体加载到内存中,然后mapAsync调用Flow

import scala.concurrent.duration._

val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].mapAsync(1) {
  case HttpRequest(HttpMethods.GET, Uri.Path("/api"), _, entity, _) =>
    val entityAsText: Future[String] = entity.toStrict(1 second).map(_.data.utf8String)

    entityAsText.map { text =>
      HttpResponse(
        StatusCodes.OK,
        entity = HttpEntity(
          ContentTypes.`text/plain(UTF-8)`,
          text
        )
      )
    }
}

根据需要调整前者的超时时间和后者的并行度。


推荐阅读