POST请求AFNetworking
:
let urlString = "http://example.com/file.php" let dictionary = ["key1": [1,2,3], "key2": [2,4,6]] var error: NSError? let data = NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.allZeros, error: &error) let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding) let parameters = ["data" : jsonString!] let manager = AFHTTPSessionManager() manager.responseSerializer = AFHTTPResponseSerializer() manager.POST(urlString, parameters: parameters, success: { requestOperation, response in let result = NSString(data: response as! NSData, encoding: NSUTF8StringEncoding)! println(result) }, failure: { requestOperation, error in })
POST请求NSURLSession
:
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!) request.HTTPMethod = "POST" let bodyData = NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.allZeros, error: &error)! request.HTTPBody = bodyData request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("\(bodyData.length)", forHTTPHeaderField: "Content-Length") NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in let result = NSString(data: data, encoding: NSUTF8StringEncoding)! println(result) }).resume()
在服务器上我有:
$data = json_decode($_POST["data"], true); if (!$data) { echo "Error: Invalid POST data"; return; } //do some stuff echo "success";
在第二种情况下,我得到"错误:无效的POST数据".我做错了什么?
这是因为AFNetworking示例没有创建JSON请求,而您的NSURLSession
示例是.AFNetworking示例正在创建application/x-www-form-urlencoded
请求(其中值是您手动创建的JSON字符串).您可以更改服务器代码以接受JSON请求,也可以将application/x-www-form-urlencoded
请求更改为请求.
如果您查看像Charles这样的AFNetworking请求主体,您可以看到它生成如下内容:
data=%7B%22key1%22%3A%5B1%2C2%2C3%5D%2C%22key3%22%3A%5B%22Harold%20%26%20Maude%22%5D%2C%22key2%22%3A%5B2%2C4%2C6%5D%7D
如果你以百分之一的方式逃避与之相关的价值data
,那就是有效的
data={"key1":[1,2,3],"key3":["Harold & Maude"],"key2":[2,4,6]}
(注意,我添加了key3
以显示转义百分比是转义标准保留字符,加上&
和+
.)
如果你想自己做这个NSURLSession
,你必须构建它,然后百分比逃脱它如下:
let allowed = NSCharacterSet.alphanumericCharacterSet().mutableCopy() as! NSMutableCharacterSet allowed.addCharactersInString("-._~") let bodyString = "data=" + jsonString.stringByAddingPercentEncodingWithAllowedCharacters(allowed)!
坦率地说,这是一种非常奇怪的方法,在application/x-www-form-urlencoded
请求中嵌入JSON .我只是将服务器更改为接受标准JSON请求($_POST
完全绕过变量):
$handle = fopen("php://input", "rb"); $raw_post_data = ''; while (!feof($handle)) { $raw_post_data .= fread($handle, 8192); } fclose($handle); $body = json_decode($raw_post_data, true);
顺便说一下,一旦服务器代码接受纯JSON请求,Swift 1.x客户端代码将是:
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!) request.HTTPMethod = "POST" request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.allZeros, error: &error)! request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in let result = NSString(data: data, encoding: NSUTF8StringEncoding)! println(result) }).resume()
AFNetworking相当于:
let urlString = "http://example.com/file.php" let dictionary = ["key1": [1,2,3], "key2": [2,4,6]] let manager = AFHTTPSessionManager() manager.requestSerializer = AFJSONRequestSerializer() manager.responseSerializer = AFHTTPResponseSerializer() manager.POST(urlString, parameters: parameters, success: { requestOperation, response in let result = NSString(data: response as! NSData, encoding: NSUTF8StringEncoding)! println(result) }, failure: { requestOperation, error in })