【问题标题】:A post request with custom parameters in SWIFTSWIFT 中带有自定义参数的发布请求
【发布时间】: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] ??

标签: json swift post alamofire


【解决方案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()
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-27
      • 2013-03-31
      • 2019-09-17
      • 2014-11-14
      • 2014-03-12
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多