带有字符串参数和数组的POST请求

时间:2016-02-04 21:08:49

标签: arrays swift post parameters request

我想发出POST请求并传递一些参数。 我想传递的参数是:

- Item : String
- Length : String
- Names : String Array
- Age : String

今天我在做这个

var URL: NSURL = NSURL(string: "URL")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)

request.HTTPMethod = "POST"
request.HTTPBody = // parameters here?
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
               (response, data, error) in
               println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

有人可以提供如何在我的请求中传递上述参数的帮助吗?我不太确定该怎么做。

2 个答案:

答案 0 :(得分:2)

问题是HTTPBody期望一个NSData对象,所以你可以在这个答案中用@dsk解释所需的数据创建Dictionary,然后将其转换为JSON以作为参数传递dataWithJSONObject函数,如下所示:

var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

var values: [String: AnyObject] = [:]
values["item"] = "value"
values["length"] = "value"
values["names"] = ["value1", "value2"]
values["age"] = "value"

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])

尽管如此,我强烈建议您使用Alamofire来更轻松地处理所有网络流程。

我希望这对你有所帮助。

答案 1 :(得分:0)

为参数添加变量:

var params: [String: AnyObject] = [:]
params["item"] = "YOUR_STRING"
params["length"] = "YOUR_STRING"
params["names"] = ["YOUR_STRING1", "YOUR_STRING2"]
params["age"] = "YOUR_STRING"

假设POST是JSON请求,请将其添加到HTTPBody中:

request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])