如何在目标c中将{“username”=“usernameValue”“password”=“passsworValue”}作为json body发布

时间:2017-01-07 09:28:14

标签: ios objective-c post afnetworking

我试过这样......

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

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

请求正文的内容类型。设置此值“Content-Type:application / json”

作为回应,我得到解码错误消息。我已经在AFNetworking中获得了获取JSON getrequest,但这个帖子请求给了我一些问题。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在第一个NSURLSession样式中,您不会将json发送到该服务。试试这样:

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