SWIFT中包含自定义参数的帖子请求

时间:2015-08-13 09:19:42

标签: json swift post alamofire

我遇到了Alamofire帖子请求的问题,如果我有一个参数:

center

帖子请求不起作用!你知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您不能将此结构作为http请求正文中编码的表单发送。也许你想把它作为json发送。在这种情况下,您可以像这样调用请求方法:

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

答案 1 :(得分:0)

此类变体有效

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

    }