使用NSURLSession复制AFNetworking POST请求

时间:2015-12-06 21:29:10

标签: swift afnetworking-2 nsurlsession

AFNetworking的POST请求:

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

NSURLSession的POST请求:

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数据"。我做错了什么?

1 个答案:

答案 0 :(得分:5)

这是因为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
})