Search code examples
iosobjective-cafnetworking

send JSON object in POST request AFNetworking , iOS


I'm using AFNetworking to post data into the web. The information I have is the URI which is baseURL/post_user_info and they want input as A JSON object containing each of the name-value pairs. In the code written below I've set the name-value pair in a dictionary. My question is how to make it's json and send it as input value?

NSString *string = [NSString stringWithFormat:@"%@?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    NSDictionary *params = @{@"input_1": @"hello world",
                             @"input_2": @"my@you.com",
                             @"input_3": @"newworldorder"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:nil];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];

[manager POST:escapedPath parameters:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] progress:nil success:^(NSURLSessionTask *task, id responseObject)
 {
     NSLog(@"%@",responseObject);
 }failure:^(NSURLSessionTask *operation, NSError *error)
 {
     NSLog(@"%@",[error localizedDescription]);
 }];

I've updated the code because now I have generated the JSON but if I run the code now it give me Error: 400 which means If input_values is empty, a bad request error will be output.


Solution

  • @interface AFJSONRequestSerializer : AFHTTPRequestSerializer

    AFJSONRequestSerializeris a subclass ofAFHTTPRequestSerializerthat encodes parameters as JSON using NSJSONSerialization.

    add this AFJSONRequestSerializer is used for send JSON not a Raw Data add this and try once

        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
    

    e.g

    NSString *string = [NSString stringWithFormat:@"%@?post_user_info",BaseURLString];
    NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
     /**************  karthik Code added  ******************/
     AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
     manager.responseSerializer = [AFHTTPResponseSerializer serializer];
     manager.requestSerializer = [AFJSONRequestSerializer serializer];
          /**************  karthik Code added  ******************/
    
        NSDictionary *params = @{@"1": @"hello world",
                                 @"2": @"my@you.com",
                                 @"3": @"newworldorder"};
    [manager POST:escapedPath parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject)
         {
             NSLog(@"%@",responseObject);
              NSError *error = nil;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
               NSLog(@"json == %@", json);
    
         } failure:^(NSURLSessionTask *operation, NSError *error) {
             NSLog(@"%@", [error localizedDescription]);
         }];
    

    Update Params

    NSDictionary *params = @{@"1": @"hello world",
                             @"2": @"my@you.com",
                             @"3": @"newworldorder"};
     NSMutableDictionary *modify = [NSMutableDictionary new];
    [modify  setObject:params forKey:@"input_values"];
    

    you get output of

    enter image description here