简体   繁体   中英

AFNetworking post parameters not encoding

I'm getting an error using AFNetworking 2.0 while using post method in Swift language because the body isn't encoded as it should be, here is my code:

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

Debugging the request I get:

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

and my server answer:

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

I don't know why the username and password is encoded like this:

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

instead of this:

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

Should AFHTTPRequestSerializer instead of AFJSONRequestSerializer .

Problem solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM