Posting JSON data using AFNetworking 2.0

2019-01-06 10:35发布

问题:

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

回答1:

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.



回答2:

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]);
}];


回答3:

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



回答4:

In swift:

Add this in manager.AFHTTPRequestOperationManager

manager.requestSerializer = AFJSONRequestSerializer(writingOptions: NSJSONWritingOptions.PrettyPrinted)


回答5:

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];