简体   繁体   English

使用C#与NSUrlSession进行HTTP POST多部分表单数据

[英]HTTP POST multipart form-data with NSUrlSession using c#

I am making a cross-platform app using xamarin forms, and I need to make Http post in the background. 我正在使用xamarin表单制作跨平台应用程序,并且需要在后台进行Http发布。

I managed to do that with a foreground service and HttpClient in Android. 我设法通过Android中的前台服务和HttpClient做到了这一点。

I am not able to do it in IOS, I am using NSUrlSession , for the backgrounding task. 我无法在IOS中执行此操作,而是将NSUrlSession用于后台任务。

I was able to do a POST with 我能够与

application/x-www-form-urlencoded; charset=UTF-8 as a Content-Type application/x-www-form-urlencoded; charset=UTF-8 as a Content-Type . application/x-www-form-urlencoded; charset=UTF-8 as a Content-Type

But I wasn't able to do it with multipart form-data. 但是我无法使用多部分表单数据来做到这一点。

I've read somewhere that I have to build the body of the request myself so I did it using some swift and objective C translations, but I was unsuccesful. 我在某个地方读到我必须自己构建请求的主体,因此我使用了一些快速而客观的C转换来完成该请求,但是我没有成功。

I tried to transform this objective c code in this answer to c# and I end up with this code, but it doesn't work, Please help! 我试图在此答案中将此目标c代码转换为c#,但最终得到了此代码,但它不起作用,请帮助!

    using (var url = NSUrl.FromString(UploadUrlString))
            using (var request = new NSMutableUrlRequest(url))
            {
                string boundaryConstant = "------WebKitFormBoundaryXXXXXXXXXX";
                request.HttpMethod = "POST";
                request["Cookie"] = "SERVERIDXXX=XXXXXX";
                var data = NSData.FromArray(ImageByteArray);
                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 += StaticData.Photos[0].Round;
                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();
            }

Found this link.. Hope it would be helpful Function name - PrepareUpload 找到了此链接。希望对您有所帮助函数名称-PrepareUpload

https://github.com/dannycabrera/SimpleBackgroundUpload/blob/master/SimpleBackgroundUpload/SimpleBackgroundUpload/AppDelegate.cs https://github.com/dannycabrera/SimpleBackgroundUpload/blob/master/SimpleBackgroundUpload/SimpleBackgroundUpload/AppDelegate.cs

The function is as followed in case the link expires 链接过期时功能如下

    /// <summary>
    /// Prepares the upload.
    /// </summary>
    /// <returns>The upload.</returns>
    public async Task PrepareUpload()
    {
        try {
            Console.WriteLine("PrepareUpload called...");

            if (session == null)
                session = InitBackgroundSession();

            // Check if task already exits
            var tsk = await GetPendingTask();
            if (tsk != null) {
                Console.WriteLine ("TaskId {0} found, state: {1}", tsk.TaskIdentifier, tsk.State);

                // If our task is suspended, resume it.
                if (tsk.State == NSUrlSessionTaskState.Suspended) {
                    Console.WriteLine ("Resuming taskId {0}...", tsk.TaskIdentifier);
                    tsk.Resume();
                }

                return; // exit, we already have a task
            }

            // For demo purposes file is attached to project as "Content" and PDF is 8.1MB.
            var fileToUpload = "UIKitUICatalog.pdf";

            if(File.Exists(fileToUpload)) {
                var boundary = "FileBoundary";
                var bodyPath = Path.Combine (Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "BodyData.tmp");

                // Create request
                NSUrl uploadHandleUrl = NSUrl.FromString (webApiAddress);
                NSMutableUrlRequest request = new NSMutableUrlRequest (uploadHandleUrl);
                request.HttpMethod = "POST";
                request ["Content-Type"] = "multipart/form-data; boundary=" + boundary;
                request ["FileName"] = Path.GetFileName(fileToUpload);

                // Construct the body
                System.Text.StringBuilder sb = new System.Text.StringBuilder("");
                sb.AppendFormat("--{0}\r\n", boundary);
                sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", Path.GetFileName(fileToUpload));
                sb.Append("Content-Type: application/octet-stream\r\n\r\n");

                // Delete any previous body data file
                if (File.Exists(bodyPath))
                    File.Delete(bodyPath);

                // Write file to BodyPart
                var fileBytes = File.ReadAllBytes (fileToUpload);
                using (var writeStream = new FileStream (bodyPath, FileMode.Create, FileAccess.Write, FileShare.Read)) {
                    writeStream.Write (Encoding.Default.GetBytes (sb.ToString ()), 0, sb.Length);
                    writeStream.Write (fileBytes, 0, fileBytes.Length);

                    sb.Clear ();
                    sb.AppendFormat ("\r\n--{0}--\r\n", boundary);
                    writeStream.Write (Encoding.Default.GetBytes (sb.ToString ()), 0, sb.Length);
                }
                sb = null;
                fileBytes = null;

                // Creating upload task
                var uploadTask = session.CreateUploadTask(request, NSUrl.FromFilename(bodyPath));
                Console.WriteLine ("New TaskID: {0}", uploadTask.TaskIdentifier);

                // Start task
                uploadTask.Resume (); 
            }
            else
            {
                Console.WriteLine ("Upload file doesn't exist. File: {0}", fileToUpload);
            }   
        } catch (Exception ex) {
            Console.WriteLine ("PrepareUpload Ex: {0}", ex.Message);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM