如何快速发送POST请求与BODY

我试图用Alamofire快速地提出一个请求。

我的JSON身体看起来像:

{ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List":[ { "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 }, { "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 } ] } 

我试图let list与NSDictionnary看起来像:

 [[Time: 30, IdQuestion: 6510, idProposition: 10], [Time: 30, IdQuestion: 8284, idProposition: 10]] 

我的请求使用Alamofire看起来像:

 Alamofire.request(.POST, "http://myserver.com", parameters: ["IdQuiz":"102","IdUser":"iOSclient","User":"iOSClient","List":list ], encoding: .JSON) .response { request, response, data, error in let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding) println(dataString) } 

请求有一个错误,我相信问题是与词典列表,因为如果我提出一个没有列表的请求,它工作正常,所以任何想法?


我已经尝试了解决schemebuild议,但我面临着同样的问题:

  let json = ["List":list,"IdQuiz":"102","IdUser":"iOSclient","UserInformation":"iOSClient"] let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted,error:nil) let jsons = NSString(data: data!, encoding: NSUTF8StringEncoding) Alamofire.request(.POST, "http://myserver.com", parameters: [:], encoding: .Custom({ (convertible, params) in var mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest mutableRequest.HTTPBody = jsons!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) return (mutableRequest, nil) })) .response { request, response, data, error in let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding) println(dataString) } 

你很近 参数字典格式不正确。 您应该尝试以下操作:

 let parameters: [String: AnyObject] = [ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List": [ [ "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 ], [ "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 ] ] ] Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON) .responseJSON { request, response, JSON, error in print(response) print(JSON) print(error) } 

希望解决你的问题。 如果没有,请回复,我会相应地调整我的答案。

如果你使用Swift 3和Alamofire v4.0,那么接受的答案将如下所示:

 let parameters: [String: Any] = [ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List": [ [ "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 ], [ "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 ] ] ] Alamofire.request("http://myserver.com", method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { response in print(response) } 

到目前为止,我还不喜欢其他答案(除SwiftDeveloper之外),因为它们要么需要反序列化JSON,要么只是重新序列化,要么关心JSON本身的结构。

在另一个问题上,afrodev已经发布了正确的答案 。 你应该去争取它。

下面是我的适应,有一些小的变化(主要是明确的UTF-8字符集)。

 let urlString = "https://example.org/some/api" let json = "{\"What\":\"Ever\"}" let url = URL(string: urlString)! let jsonData = json.data(using: .utf8, allowLossyConversion: false)! var request = URLRequest(url: url) request.httpMethod = HTTPMethod.post.rawValue request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type") request.httpBody = jsonData Alamofire.request(request).responseJSON { (response) in print(response) } 

Xcode 8.X,Swift 3.X

易于使用;

  let params:NSMutableDictionary? = [ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List": [ [ "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 ], [ "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 ] ] ]; let ulr = NSURL(string:"http://myserver.com" as String) let request = NSMutableURLRequest(url: ulr! as URL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted) let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue) if let json = json { print(json) } request.httpBody = json!.data(using: String.Encoding.utf8.rawValue); Alamofire.request(request as! URLRequestConvertible) .responseJSON { response in // do whatever you want here print(response.request) print(response.response) print(response.data) print(response.result) } 

我想通知的变化很less。 从现在开始,可以从响应对象访问请求,JSON,错误。

  let urlstring = "Add URL String here" let parameters: [String: AnyObject] = [ "IdQuiz" : 102, "IdUser" : "iosclient", "User" : "iosclient", "List": [ [ "IdQuestion" : 5, "IdProposition": 2, "Time" : 32 ], [ "IdQuestion" : 4, "IdProposition": 3, "Time" : 9 ] ] ] Alamofire.request(.POST, urlstring, parameters: parameters, encoding: .JSON).responseJSON { response in print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } response.result.error } 

我稍微编辑了SwiftDeveloper的答案,因为它不适合我。 我也添加了Alamofirevalidation。

 let body: NSMutableDictionary? = [ "name": "\(nameLabel.text!)", "phone": "\(phoneLabel.text!))"] let url = NSURL(string: "http://server.com" as String) var request = URLRequest(url: url! as URL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let data = try! JSONSerialization.data(withJSONObject: body!, options: JSONSerialization.WritingOptions.prettyPrinted) let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue) if let json = json { print(json) } request.httpBody = json!.data(using: String.Encoding.utf8.rawValue) let alamoRequest = Alamofire.request(request as URLRequestConvertible) alamoRequest.validate(statusCode: 200..<300) alamoRequest.responseString { response in switch response.result { case .success: ... case .failure(let error): ... } } 

{

  if Reachability.isConnectedToNetwork() == true { let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = .indeterminate hud.label.text = "Loading" hud.animationType = .fade var request = URLRequest(url: URL(string: "http://skandal24.serv.si/ws/webservice/forgot_password")!) request.httpMethod = "POST" let postString = String(format: "email=%@&lang=%@", arguments: [txt_emailVirify.text!, language!]) print(postString) emailString = txt_emailVirify.text! request.httpBody = postString.data(using: .utf8) request.addValue("delta141forceSEAL8PARA9MARCOSBRAHMOS", forHTTPHeaderField: "Authorization") request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") Alamofire.request(request).responseJSON { response in //Your code print(response.value) if response.response?.statusCode == 200 { let dictionary = (response.value) as! AnyObject let status = dictionary.value(forKey: "status") as! String let sts = Int(status) DispatchQueue.main.async() { if sts == 200 { } } } else { } } } else { } }