How to represent a form-data request using Akka HTTP?

一曲冷凌霜 提交于 2019-12-11 15:49:52

问题


I want to create a form-data http request to Facebook API using Akka HTTP. In curl, the request example looks like:

curl \
 -X POST \
 "https://graph-video.facebook.com/v2.3/1533641336884006/videos"  \
 -F "access_token=XXXXXXX" \
 -F "upload_phase=transfer" \
 -F "start_offset=0" \
 -F "upload_session_id=1564747013773438" \
 -F "video_file_chunk=@chunk1.mp4"

So I created a following model for a request payload representation:

case class FBSingleChunkUpload(accessToken: String, 
    sessionId: String,
    from: Long, 
    to: Long, 
    file: File) //file is always ~1Mb

Then I'm going to use:

Http().cachedHostConnectionPoolHttps[String]("graph-video.facebook.com")

But I don't know how to convert FBSingleChunkUpload to the correct HttpRequest :(

Can you give me a hint, how to represent a such type of requests using Akka HTTP?


回答1:


There is an FormData Entity type for that

 val fBSingleChunkUpload = ???
 HttpRequest(method = HttpMethods.POST,
              entity = FormData(("accessToken", fBSingleChunkUpload.accessToken), ...).toEntity)

Additionally for the file you could check if it works with Multipart.FormData

 val fileFormPart = Multipart.FormData
    .BodyPart("name", HttpEntity(MediaTypes.`application/octet-stream`, file.length(), FileIO.fromPath(file.toPath)))

  val otherPart = Multipart.FormData.BodyPart.Strict("accessToken", "the token")

  val entity =
    Multipart.FormData(otherPart, fileFormPart).toEntity



回答2:


In curl, the -F option stipulates a POST using the "multipart/form-data" content type. To create such a request in Akka HTTP, use Multipart.FormData (defaultEntity below is borrowed from Akka HTTP's MultipartSpec):

val chunkUpload = FBSingleChunkUpload(...)

def defaultEntity(content: String) =
  HttpEntity.Default(ContentTypes.`text/plain(UTF-8)`, content.length, Source(ByteString(content) :: Nil))

val streamed = Multipart.FormData(Source(
  Multipart.FormData.BodyPart("access_token", defaultEntity(chunkUpload.accessToken)) ::
  Multipart.FormData.BodyPart("upload_phase", defaultEntity("transfer")) ::
  Multipart.FormData.BodyPart("start_offset", defaultEntity(chunkUpload.from.toString)) ::
  Multipart.FormData.BodyPart("upload_session_id", defaultEntity(chunkUpload.sessionId)) ::
  Multipart.FormData.BodyPart.fromFile(
    "video_file_chunk", ContentType.Binary(MediaTypes.`video/mp4`), chunkUpload.file
  ) :: Nil))

val request =
  HttpRequest(method = HttpMethods.POST, uri = /** your URI */, entity = streamed.toEntity)


来源:https://stackoverflow.com/questions/50046266/how-to-represent-a-form-data-request-using-akka-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!