当前位置:  开发笔记 > 编程语言 > 正文

使用NSURLSession复制AFNetworking POST请求

如何解决《使用NSURLSession复制AFNetworkingPOST请求》经验,为你挑选了1个好方法。

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



1> Rob..:

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

推荐阅读
郑谊099_448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有