简体   繁体   English

SWIFT中具有自定义参数的发布请求

[英]A post request with custom parameters in SWIFT

I got a problem with Alamofire post request what if I have a parameters like : 我在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)

the post request won't work ! 邮寄要求无效! do you have any idea how to solve that ? 你有解决的办法吗?

You cannot send that structure as form encoded in the http request body. 您不能以http请求正文中编码的形式发送该结构。 Maybe you'd like to send it as json. 也许您想将其作为json发送。 In that case you can invoke request method like this: 在这种情况下,您可以像这样调用请求方法:

Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)

Such variant works 这样的变体作品

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)
        }

//place function code upper the action where you posting your data //将功能代码放在发布数据的操作上方

 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()

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM