AFNetworking发布参数不编码

时间:2015-09-06 01:23:28

标签: ios swift swift2 afnetworking-2

我在Swift语言中使用post方法时使用AFNetworking 2.0收到错误,因为正文没有编码,这是我的代码:

let manager = AFHTTPRequestOperationManager()
manager.securityPolicy.allowInvalidCertificates = true;

let reqSerializer: AFJSONRequestSerializer = AFJSONRequestSerializer()
reqSerializer.setValue("T-Rex", forHTTPHeaderField: "User-Agent")
reqSerializer.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
reqSerializer.setValue("apikey", forHTTPHeaderField: "Authorization")
manager.requestSerializer = reqSerializer

let resSerializer: AFJSONResponseSerializer =  AFJSONResponseSerializer()
resSerializer.acceptableContentTypes = ["text/html", "application/json"]
manager.responseSerializer = resSerializer;
let params: NSDictionary = ["userName" : userName, "passWord" : passWord]

manager.POST(Constants.apiURL.url + "users/login",
    parameters:params,
    success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
        NSLog("Success! Response is \(responseObject.description)")
    },
    failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
        NSLog("Failure! Error is: \(error.localizedDescription)")
})

调试我得到的请求:

POST 'http://api.cc/users/login': {
    Accept = "application/json";
    "Accept-Language" = "pt;q=1, fr;q=0.9, en;q=0.8";
    Authorization = apikey;
    "Cache-Control" = "no-cache";
    "Content-Type" = "application/json";
    "User-Agent" = "T-Rex";
} {"passWord":"123","userName":"123"}

我的服务器回答:

400 'http://api.cc/users/login' [0.7545 s]: {
    Age = 0;
    Connection = "keep-alive";
    "Content-Length" = 83;
    "Content-Type" = "application/json";
    Date = "Sun, 06 Sep 2015 01:03:00 GMT";
    Server = "nginx/1.8.0";
    Via = "1.1 varnish-v4";
    "X-Varnish" = 950329;
} {"error":true,"message":"Required field(s) userName, passWord is missing or empty"}

我不知道为什么用户名和密码编码如下:

{"passWord":"123","userName":"123"}

而不是:

{"passWord:123&userName":123"}

1 个答案:

答案 0 :(得分:0)

AFHTTPRequestSerializer代替AFJSONRequestSerializer

问题解决了。