SWIFT 中带有自定义参数的发布请求
Posted
技术标签:
【中文标题】SWIFT 中带有自定义参数的发布请求【英文标题】:A post request with custom parameters in SWIFT 【发布时间】:2015-08-13 09:19:42 【问题描述】:我在使用 Alamofire 发布请求时遇到问题,如果我有如下参数:
let parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
[["x": 1],["y": 2]],
[["x": 1],["y": 2]],
[["x": 1],["y": 2]]
]
]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters)
发布请求不起作用!你知道如何解决这个问题吗?
【问题讨论】:
你的意思是 "baz" : ["a" : 1] ?? 【参考方案1】:您不能将该结构以编码在 http 请求正文中的形式发送。也许您想将其作为 json 发送。在这种情况下,您可以像这样调用请求方法:
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)
【讨论】:
【参考方案2】:这种变体有效
let parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
[["x": 1],["y": 2]],
[["x": 1],["y": 2]],
[["x": 1],["y": 2]]
]
]
let data = NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted,error:nil)
let post = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
httpPost("http://httpbin.org/post", postData: post)res, code in
println(res)
//将功能代码放在您发布数据的操作上方
func httpPost(url:String, postData: String, completion: (String, Int) -> Void)
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding);
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/44.0.2403.125 Safari/537.36", forHTTPHeaderField: "User-Agent")
request.addValue("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", forHTTPHeaderField: "Accept")
request.addValue("gzip, deflate, sdch", forHTTPHeaderField: "Accept-Encoding")
request.addValue("max-age=0", forHTTPHeaderField: "Cache-Control")
var session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: data, response, error in
if let HTTPResponse = response as? NSHTTPURLResponse
let statusCode = HTTPResponse.statusCode
completion(NSString(data: data, encoding: NSUTF8StringEncoding) as! String, statusCode)
)
task.resume()
【讨论】:
以上是关于SWIFT 中带有自定义参数的发布请求的主要内容,如果未能解决你的问题,请参考以下文章