我正在使用 xamarin 表单制作一个跨平台应用程序,我需要在后台进行 Http post。
我成功地通过 Android 中的前台服务和 HttpClient
做到了这一点。
我无法在 IOS 中执行此操作,我正在使用 NSUrlSession
来执行后台任务。
我能够使用
进行 POSTapplication/x-www-form-urlencoded; charset=UTF-8 作为内容类型
。
但我无法使用多部分表单数据来做到这一点。
我在某处读到过,我必须自己构建请求的正文,因此我使用一些快速且客观的 C 翻译来完成它,但我没有成功。
我试图在这个answer中转换这个 objective-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();
}
最佳答案
找到这个链接..希望有帮助 函数名称-PrepareUpload
链接过期时的功能如下
/// <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);
}
}
关于c# - 使用 C# 与 NSUrlSession 的 HTTP POST 多部分表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57199682/