【问题标题】:Scala and Akka HTTP: Processing form-data requestsScala 和 Akka HTTP:处理表单数据请求
【发布时间】:2020-04-24 10:13:55
【问题描述】:

假设我们有以下请求:

curl --location --request POST 'localhost:8080/api' \
--header 'Content-Type: multipart/form-data' \
--form 'field1=value1' \
--form 'field2=value2'

下面的请求处理程序获取整个实体,但我正在努力寻找如何获取value1value2

val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].mapAsync(1) {
  case HttpRequest(HttpMethods.POST, Uri.Path("/api"), _, entity, _) =>
    val entityTextFuture: Future[String] = entity.toStrict(3 seconds).map(_.data.utf8String)
      entityTextFuture.flatMap { text =>
        Future(HttpResponse(
          StatusCodes.OK,
          entity = text
        ))
      }
}

重要提示:我必须使用 Akka HTTP 低级服务器 API,所以不能使用路由。

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

【问题讨论】:

    标签: scala httprequest multipartform-data httpresponse akka-http


    【解决方案1】:

    如果您想要的只是表单数据中的字符串值,您只需解组为StrictForm,然后将每个字段值解组为字符串。

    这是一个概念验证 Ammonite 脚本,它使用 value1 & value2 响应您的 curl 请求:

    import $ivy.`com.typesafe.akka::akka-actor:2.6.3`
    import $ivy.`com.typesafe.akka::akka-stream:2.6.3`
    import $ivy.`com.typesafe.akka::akka-http:10.1.11`
    
    import scala.concurrent.Future
    
    import akka.actor.ActorSystem
    import akka.stream.scaladsl.Flow
    import akka.http.scaladsl.Http
    import akka.http.scaladsl.model._
    import akka.http.scaladsl.unmarshalling.Unmarshal
    import akka.http.scaladsl.common.StrictForm
    
    implicit val system = ActorSystem()
    implicit val ec = system.dispatcher
    
    val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].mapAsync(1) {
      case HttpRequest(HttpMethods.POST, Uri.Path("/api"), _, entity, _) =>
        for {
          strictForm <- Unmarshal(entity).to[StrictForm]
          fieldsSeq <- Future.traverse(strictForm.fields) {
            case (n, v) => Unmarshal(v).to[String].map(n -> _)
          }
          fields = fieldsSeq.toMap
          response = fields("field1") + " & " + fields("field2")
        } yield HttpResponse(StatusCodes.OK, entity = response)
    }
    
    Http().bindAndHandle(requestHandler, "localhost", 8080)
    

    【讨论】:

    • Alec 它就像一个魅力!非常感谢您的时间和帮助!
    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2018-12-07
    • 2013-05-17
    相关资源
    最近更新 更多