Posting JSON data using AFNetworking 2.0
Asked Answered
T

5

44

I have a web script which accepts JSON string as input through HTTP POST request. I have came across several AFNetworking 1.x example for the same , can anybody please point me or give AFNetworking 2.0 example to do an HTTP POST request to a web script with formatted JSON as input ?

Thanks

Ternary answered 31/1, 2014 at 18:15 Comment(4)
Read the migration guide on the AFNetworking github page.Congregationalism
problem is i m new to AFNetworking so i don't really know and wish to understand the previous versions I m coming from ASIHTTP background thanks for suggestion though.Ternary
Search for JSON and POST on cocoadocs.org/docsets/AFNetworking/2.1.0 you need to try something and then ask for help...Congregationalism
@wain i wish it was so obvious that even a beginner would understandTernary
T
78

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:params
success:^(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.

Ternary answered 10/2, 2014 at 8:21 Comment(7)
this did not work for me. i keep getting this error status code: 200, headers { Connection = close; "Content-Length" = 59; "Content-Type" = "text/html; charset=UTF-8"; Date = "Mon, 21 Apr 2014 06:44:34 GMT"; Server = "Apache/2.2.25 (Amazon)"; "X-Powered-By" = "PHP/5.3.27"; } }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}Chenee
@Chenee you ignored my last statement in the answer :) "Also don't forget to set response header type in the server script as Application/json"Ternary
You can check this answer for the JSON parser to accept "text/html" content type if you can't change de server script.Trimetrogon
@Trimetrogon setting response type as text/html and sending JSON is bad practice no standard API does that.Ternary
This doesn't work for me too. I am getting "JSON text did not start with array or object and option to allow fragments not set."Zelazny
NSCocoaErrorDomain Code=3840Zelazny
this might help you #21452885Ternary
B
20

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]);
}];
Backbend answered 16/9, 2014 at 13:21 Comment(2)
I'm not sure, but this is not working anymore. Please check this question.Beekman
I didn't checked it for newer version of AFNetworking. Surely it works on 2.4.1 version.Backbend
L
8

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. :)

Lemcke answered 25/5, 2015 at 2:16 Comment(1)
That worked, Thanks. Please rate up my answers as well :)Cuffs
P
5

In swift:

Add this in manager.AFHTTPRequestOperationManager

manager.requestSerializer = AFJSONRequestSerializer(writingOptions: NSJSONWritingOptions.PrettyPrinted)
Poverty answered 19/8, 2016 at 19:4 Comment(0)
D
2

if you want to post parameter dictionary json string use following code

NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"your_webservice_post_url"]];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *error;
NSDictionary *parameters = @{@"customValue":@"value"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
 [urlRequest setHTTPMethod:@"POST"];
 [urlRequest setHTTPBody:jsonData];
Durst answered 28/4, 2016 at 13:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.