多部分表单上载和NSURLSession.uploadTaskWithRequest之间的区别

编程入门 行业动态 更新时间:2024-10-11 13:23:56
本文介绍了多部分表单上载和NSURLSession.uploadTaskWithRequest之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

来自网络编程世界,我对使用多部分表单请求上传文件非常满意。但是,在iOS中,我们有一个名为 NSURLSession 的东西,方法是 uploadTaskWithRequest ,这似乎是要调用的方法做图像上传等。

Coming from the world of web programming, I'm pretty much comfortable with working with multipart form requests to upload files. However, in iOS, we have a thing called NSURLSession with the method uploadTaskWithRequest, which seems to be the method to call to do image uploads and the likes.

你能解释两种方法之间的区别吗,多部分表格上传 vs uploadTaskWithRequest ?如果我已经有一个处理多部分表单上传的后端,我可能需要进行哪种调整以便它还支持 uploadTaskWithRequest ?

Can you explain the difference between the two approach, multipart form upload vs uploadTaskWithRequest? If I already have a backend that handle multipart form uploads, what kind of adjustments that I might need so that it support uploadTaskWithRequest as well?

推荐答案

uploadTaskWithRequest 只需发送 NSData ,文件,或作为请求的主体流。它没有做任何事情。它只是具有可以与后台会话一起使用的好处。

The uploadTaskWithRequest simply sends the NSData, file, or stream as the body of the request. It doesn't do anything beyond that. It simply has the benefit that it can be used with background sessions.

因此,如果您的Web服务需要 multipart / form-data 请求,您必须自己构建该请求(除非您使用AFNetworking或Alamofire之类的东西为您执行此操作)。一旦构建了该请求,就可以使用 dataTaskWithRequest (已设置 HTTPBody NSMutableURLRequest )或 uploadTaskWithRequest (在这种情况下,您不设置 HTTPBody ,而是将其作为参数提供给 uploadTaskWithRequest )。

So, if you have web service that is expecting multipart/form-data request, you have to build that request yourself (unless you use something like AFNetworking or Alamofire to do this for you). Once you've built that request, you can either use dataTaskWithRequest (having set the HTTPBody of the NSMutableURLRequest) or uploadTaskWithRequest (in which case you don't set HTTPBody, but rather provide it as a parameter to uploadTaskWithRequest).

顺便说一下,像 Charles 在这些情况下非常有用,让您可以观察幕后发生的事情。

By the way, a tool like Charles is very useful in these cases, letting you observe what's going on behind the scenes.

更多推荐

多部分表单上载和NSURLSession.uploadTaskWithRequest之间的区别

本文发布于:2023-10-10 21:23:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479785.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   区别   NSURLSession   uploadTaskWithRequest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!