Scala和Akka HTTP:处理表单数据请求

Stratos K

假设我们有以下要求:

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,因此无法使用路由。

非常感谢您的宝贵时间和事先的帮助!

亚历克

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

这是概念证明Ammonite脚本,它通过以下方式响应您的curl请求value1 & value2

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用Akka HTTP表示表单数据请求?

Python 3 POST请求来处理表单数据

node.js处理表单数据请求

Akka HTTP:ByteString作为表单数据请求中的文件有效负载

Scala和Akka HTTP:请求内的请求和线程问题

Spring Boot:发布和处理具有多个主体部分的多部分/表单数据请求

使用sttp的多部分表单数据请求-Scala HTTP客户端

Scala和akka-http rest服务的断路器

在Express中获取POST和GET请求的表单数据

如何用kemal和Crystal处理html表单数据

使用 Deno 和 Oak 处理多部分/表单数据

使用Python CGI脚本处理表单数据

AngularJS $ http发布文件和表单数据

发送和处理表格数据

无法发布多部分数据和requestbody表单数据json请求

Angular 2表单数据和JSON数据发布在同一请求中

preventDefault 和 type submit 如何处理表单?

使用JS和JQuery处理表单输入

Django处理表单数据而无需使用Django创建表单

带有resteasy和多部分/表单数据请求的最大文件大小

如何同时使用正文和表单数据发出 axios post 请求?

NodeJS-编辑和代理多部分/表单数据请求

处理表单之间的数据

Alamofire的无效证书,表单数据和HTTP标头数据

使用 Azure Function .NET5 和 HttpRequestData,如何处理文件上传(表单数据)?

在ColdFusion上使用JSoup处理表单数据服务器端

Symfony2:在处理表单数据之前,有什么好的模式?

在控制器中处理表单数据以创建新字段-Rails

如何在操作页面上创建特定功能来处理表单数据?