skip to Main Content

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 "[email protected]"

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?

2

Answers


  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
    
    Login or Signup to reply.
  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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search