URLSessionDataTask – upload parameters with multipart/form-data content type

Issue

This Content is from Stack Overflow. Question asked by Libor Zapletal

I would like to create body like in this curl example:

curl --location --request POST 'https://request.url' 
--header 'Authorization: Bearer xxx' 
--form 'name="Name"' 
--form 'data="[{"text": "This is comment", "another": "Thomas"}]"'

How can I implement this and correctly set httpBody in URLRequest?

I tried different approaches but nothing seems to work. Simple:

let body = NSMutableData()
body.appendString("name=" request.name))
body.appendString("data=" + "[{"text": "This is comment", "another": "Thomas" }]"))
return Data(body)

Then I tried to prepand: "Content-Disposition: form-data;". Or added line breakers. Nothing seems to be working.

That lines of code are part of class that helps me work with requests. What’s the simplest way to get it working? Thanks for help



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?