HTTP POST Request multipart/form-data

CrossSharpCrossSharp Member ✭✭
edited July 25 in Xamarin.iOS

Hello, I am making a cross-platform app and I need to make some POST request in the background I managed to do that for Android with HttpClient and I am using NSUrlSessionto achieve this for IOS.

I was able to make a normal HTTP post with string params but I can't figure out how to do it with a multipart/form-data as a content type.

Can someone please guide me through this, I am literally stuck for like a week.

I found some swift and objective C code, but unfortunately, I know nothing about these two languages.

Please help!

This is my code for the moment, I've read somewhere that I have to write the body myself, I tried that but it didn't work.

using (var url = NSUrl.FromString(UploadUrlString))
using (var request = new NSMutableUrlRequest(url))
{
string boundaryConstant = "------WebKitFormBoundaryizZlLeb5a0mTyHtJ";
request.HttpMethod = "POST";
request["Cookie"] = "SERVERIDxxx=xxxxxx";
var data = NSData.FromArray(MyPhotoByteArray);
var uiimage = UIImage.LoadFromData(data);
NSData img = uiimage.AsJPEG(1);
string Body = boundaryConstant+ "\r\n";
Body += "Content-Disposition: form-data; name=\"id\"\r\n\r\n";
Body += 50000+ "\r\n";
Body += boundaryConstant + "\r\n";
Body += "Content-Disposition: form-data; name=\"upload_file\"; filename=\"Untitled.png\"\r\n";
Body += "Content-Type: image/png\r\n\r\n";
Body+=img+ "\r\n";
Body += boundaryConstant + "--";
request.Body = NSData.FromString(Body);
request["Content-Type"] = "multipart/form-data; boundary="+ boundaryConstant;
NSUrlSessionDownloadTask downloadTask = session.CreateDownloadTask(request);
downloadTask.Resume();
}

Answers

  • TedRogersTedRogers USMember ✭✭✭✭

    @CrossSharp

    I am puzzled by these two lines:

    NSUrlSessionDownloadTask downloadTask = session.CreateDownloadTask(request);
    downloadTask.Resume();

    If you are trying to do a POST, it should be an upload task.

    How I did this was to capture my HttpClient request using Fiddler and then effectively reverse engineer it to create the body for iOS.

    Ted

Sign In or Register to comment.