scala - 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)
如何获取实体的字符串内容?
提前谢谢了!
解决方案
一种方法是调用toStrict
,RequestEntity
将实体加载到内存中,然后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
)
)
}
}
根据需要调整前者的超时时间和后者的并行度。
推荐阅读
- rust - pub 和 pub(super) 什么时候有不同的语义?
- python - 使用一行多重赋值在列表中交换元素
- javascript - 使用 JavaScript + PHP 导出 Excel 文件时出错(文件为空白)
- node.js - 接收错误:使用邮递员向 AWS S3 api 提交 POST 请求时连接 ECONNREFUSED
- r - 消失的柱子 (R)
- python - 如何将 CSV 文件中的内容附加到代码列的单元格 = 'AAPL' 的所有行中的列?
- bash - 在终端中通过 Emacs 查看手册页
- python - 安装 os_sys 软件包时遇到问题,接收 os_sys 有无效的车轮错误
- python - 使用 numpy 和 numba Python 优化计算
- python - “sanic”python中的占位符