Search code examples
iosobjective-cpostafnetworking

How to POST { "username"="usernameValue" "password"="passsworValue" } as json body in objective c


I tried Like this..

-(void)GetCartIdDetails{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *post = [NSString stringWithFormat:@"username=%@&pasword=%@",self.TextUsername.text,self.TextPassword.text];
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:@"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"]];

        [request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:postData];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

        //MultiThreading
        if (postData){
            dispatch_async(dispatch_get_main_queue(), ^{
                [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

                    //removing Double Qoutes From String
                    NSString *Replace =[requestReply stringByReplacingOccurrencesOfString:@"\"" withString:@""];

                    NSLog(@"requestReply: %@", Replace);

                }] resume];
            });
        }
    });
}

Using AFNetworking:

-(void)Gettok {

    NSString* URLString = [NSString stringWithFormat:@"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];

    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


    manager.requestSerializer = requestSerializer;

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:self.TextUsername.text forKey:@"username"];
    [params setObject:self.TextPassword.text forKey:@"password"];

        [manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSError * error;
             NSArray *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
            NSLog(@"--------------------respons : %@--------------------",result);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"----------------------Error ; %@------------------------------",error);
        }];
}

The content type of the request body. Set this value "Content-Type:application/json"

In response i get decode error message.I already got the get JSON getrequest working in AFNetworking but this post request is giving me some problems. Thanks for help in advance.


Solution

  • In the first NSURLSession style you don't send json to the service. Try it like this:

    -(void)GetCartIdDetails{
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSDictionary *dict = @{@"username":self.TextUsername.text,
                                       @"password":self.TextPassword.text};
    
    
                         NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
                           NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
                           NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
                           [request setURL:[NSURL URLWithString:@"http://192.168.0.21/mahroosa/rest/V1/integration/customer/token"]];
    
                           [request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
                           [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                           [request setHTTPMethod:@"POST"];
                           [request setHTTPBody:postData];
                           NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
                           //MultiThreading
                           if (postData){
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                       NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    
                                       //removing Double Qoutes From String
                                       NSString *Replace =[requestReply stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    
                                       NSLog(@"requestReply: %@", Replace);
    
                                   }] resume];
                               });
                           }
                });
    }