Posting JSON data using AFNetworking 2.0 Posting JSON data using AFNetworking 2.0 ios ios

Posting JSON data using AFNetworking 2.0


after searching docs and trying out some codes I got following as an example

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.requestSerializer = [AFJSONRequestSerializer serializer];NSDictionary *params = @ {@"user" :txtUserName, @"pwd" :txtPwd };[manager POST:URL_SIGNIN parameters:paramssuccess:^(AFHTTPRequestOperation *operation, id responseObject){    NSLog(@"JSON: %@", responseObject);}failure: ^(AFHTTPRequestOperation *operation, NSError *error) {     NSLog(@"Error: %@", error); }];

Also don't forget to set response header type in the server script as Application/json.


Here is some simple template for POST parameters stored in NSMutableDictionary parameters in JSON format. Works with AFNetworking 2.4.1.

NSString *baseURL = @"http://your-server.com/";NSString *path = @"method/url/";NSMutableDictionary *parameters = [NSMutableDictionary dictionary];[parameters setObject:@"value" forKey:@"key"];AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];manager.requestSerializer = [AFJSONRequestSerializer serializer];manager.responseSerializer = [AFJSONResponseSerializer serializer];[manager POST:path parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {        NSLog(@"JSON: %@", responseObject);        //here is place for code executed in success case} failure:^(NSURLSessionDataTask *task, NSError *error) {        //here is place for code executed in error case        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error while sending POST"                                                            message:@"Sorry, try again."                                                           delegate:nil                                                  cancelButtonTitle:@"Ok"                                                  otherButtonTitles:nil];        [alertView show];        NSLog(@"Error: %@", [error localizedDescription]);}];


If you want to post json to server, you should post your parameters use this way below.

Use this way , you can then find out the "Content-Type" in your request header is "application/json".

AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];manager.requestSerializer = serializer; NSDictionary *paras = @{@"uid" : @(10020)};[manager POST:@"http://your.request.url" parameters:paras success:^(AFHTTPRequestOperation *operation, id responseObject) {}failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"the falire is %@", error);}];

May this help. :)