scala - 如何使用 akka-http 在 Post 请求中一起发送文件和 json 负载

标签 scala curl akka akka-http

我必须在我的 akka 代码中发送以下curl POST 请求,它在请求中发送 json 负载和文件:

curl \
  -F "payload=</tmp/upload_file_payload.json" \
  -F "file=@/tmp/file.pdf" \
   -v https://host/api

我正在尝试在 akka-http 中实现相同的功能,但不确定具体该怎么做。我找到了一些例子herehere ,但它不能按原样工作,所以我编写了以下代码,其中也有一些错误,但看起来我很接近:

val httpEntity = HttpEntity(MediaTypes.`application/octet-stream`, file, 100000)
//    val httpEntity = HttpEntity.fromPath(ContentType.apply(MediaTypes.`application/octet-stream`), Paths.get(file.getAbsolutePath))
val fileFormData = Multipart.FormData.BodyPart.Strict("file", httpEntity, Map.empty)
val jsonFormData = Multipart.FormData.BodyPart.Strict("payload", payload, Map.empty)


//      Multipart.FormData.Strict(scala.collection.immutable.Seq(jsonFormData, fileFormData)).toEntity()
val entity = Multipart.FormData( Source(List(jsonFormData, fileFormData))).toEntity()
val httpRequest = HttpRequest(HttpMethods.POST, uri = uri, entity = entity)

但是这段代码无法编译。

在这期间,当我编译代码时,出现错误:

411 Length Requered

我尝试添加 Content-Length header 与请求,但无济于事。

最佳答案

最后,在查看了 akka-http 代码和更多尝试之后,终于我得到了如下的工作,注释中的解释:

val httpEntity = HttpEntity(MediaTypes.`application/octet-stream`, file, 100000).toStrict(10.seconds)(mat)   // I had to convert this into strict: which adds Content-Length and tells it is not streaming
val fileFormData = Multipart.FormData.BodyPart.Strict("file", Await.result(httpEntity, 10.seconds), Map.empty)  // used Await here to get httpEntity from Future, this might be made better
val jsonFormData = Multipart.FormData.BodyPart.Strict("payload", payload, Map.empty)

val entity = Multipart.FormData(jsonFormData, fileFormData).toEntity() // Corrected this signature
val httpRequest = HttpRequest(HttpMethods.POST, uri = uri, entity = entity)

为了避免 411 错误,我必须使 FormData 严格,它本身会添加所需的 Content-Length header 。

关于scala - 如何使用 akka-http 在 Post 请求中一起发送文件和 json 负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47397585/

相关文章:

docker - 无法从容器内访问Docker API

scala - 无法使用akka java api的UnTypedActorFactory创建 Actor

java - 定义 Akka Actor Count 的最佳实践是什么

java - Scala: 'val' 没有初始化

scala - 使用函数式编程解决动态编程问题

curl - curl -输出到终端的内容是什么?

akka - 在 spray-json 中解码嵌套的 json

postgresql - Slick 中具有不同数据类型的列的左连接

scala - 在Scala的Seq中添加项目

docker - WSL-Docker : curl: (60) SSL certificate problem: unable to get local issuer certificate