xcode iOS中的HTTP“POST”请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9348746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:21:03  来源:igfitidea点击:

HTTP "POST" request in iOS

iosxcodehttprequest

提问by OAZ

I need to post to this url: https://api.platform.com/media. I am really new to HTTP request and I need to send a request that contains an image and 3 other parameters. I have the values that I need but I don't know where to begin or how it works.... Headers, Content-Lengthand some other wired values.

我需要发布到这个网址:https://api.platform.com/media。我对 HTTP 请求非常陌生,我需要发送一个包含图像和其他 3 个参数的请求。我有我需要的值,但我不知道从哪里开始或它是如何工作的......标头Content-Length和其他一些有线值。

These are the values:

这些是值:

media[user_profile_id]
media[channels_list][]
media[file]

回答by Marcus

Create an instance of NSURLRequest. Set the method property to POST, and set the body data.

创建一个 NSURLRequest 的实例。将方法属性设置为 POST,并设置正文数据。

The data needs to be a single instance of NSData, so you will have to keep appending whatever data you want to send, each field labeled and separated by ampersands like so:

数据需要是 NSData 的单个实例,因此您必须继续附加要发送的任何数据,每个字段都用&符号标记和分隔,如下所示:

id=12345&channels=1,2,3&image=123abcdef

id=12345&channels=1,2,3&image=123abcdef

Remember, you need to transform all strings to binary, using NSString's dataUsingEncoding: method. If you are using UIImage for the image, it has a similar method.

请记住,您需要使用 NSString 的 dataUsingEncoding: 方法将所有字符串转换为二进制。如果你使用 UIImage 作为图像,它有一个类似的方法。

The server of course needs to know how to parse the data, strings being strings and the image being an image.

服务器当然需要知道如何解析数据,字符串是字符串,图像是图像。

Finally, create an instance of NSURLConnection, set your current object as delegate and implement the delegate protocol to receive the response.

最后,创建一个 NSURLConnection 实例,将当前对象设置为委托并实现委托协议以接收响应。

回答by Simon Germain

Lookup NSMutableURLRequest. You can use that with NSURLConnection.

查找 NSMutableURLRequest。您可以将其与 NSURLConnection 一起使用。

This postshould give you a better idea of how to do it.

这篇文章应该能让你更好地了解如何做到这一点。