Scala和Akka HTTP:读取具有多个字段的有效负载

问题描述 投票:0回答:1

我正在尝试在Akka HTTP中创建一个HTTP请求,该HTTP请求将能够通过HTTP请求发送两个字符串“ string1”和“ string2”。

我目前有以下代码可以处理一个简单的请求:

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
        )
      )
    }
}

但是我不知道如何处理有效负载中的多个字符串。

如果MultiPart是上述问题的解决方案,请您说明如何完成?我一直无法从网上找到的一些资源中了解如何做到这一点。

非常感谢您的时间和提前的帮助!

scala akka akka-http
1个回答
0
投票

[如果您的意思是在一个http请求中发送多行,则除了将收到的字符串分成几行外,无需执行任何其他操作。

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 =>
          val lines = text.split("\\r?\\n")
          HttpResponse(
            StatusCodes.OK,
            entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, s"Got ${lines.length} lines")
          )
        }
    }

测试中

curl -X GET http://localhost:8080/api -d 'start
2
3
end'

Got 4 lines⏎

旁注,GET应该没有主体使用,而应该使用PUT或POST。在此处阅读更多内容HTTP GET with request body

© www.soinside.com 2019 - 2024. All rights reserved.