简体   繁体   中英

AFNetworking: Get JSON Value From Http Response

I am primarily an android developer and really new to IOS. I am using AFNetworking 1.0 since I am working with an existing source and I am sending a standard http Post request and returning the data like so:

   //Sending the post request and getting the result
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://testsite.org/mobile_app"]];
    [httpClient setParameterEncoding:AFFormURLParameterEncoding];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                            path:@"http://testsite.org/mobile_app/studentregister.php"
                                                      parameters:@{@"username":username, @"displayname":displayname, @"password":password, @"passwordc":passwordc, @"email":email, @"teacherCode":teacherCode}];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        // Print the response body in text
        NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation start];

the response should contain the JSON data which looks like this according to burp suit:

{"userCharLimit":"Your username must be between 5 and 25 characters in length"}

{"displaynameCharLim":"Your displayname must be between 5 and 25 characters in length"}

{"passLimit":"Your password must be between 8 and 50 characters in length"}

{"emailInvalid":"Not a valid email address"}

{"teacherCodeLength":"Your teacher code is not 5 to 12 characters"}.

How can I get those JSON values? I have seen a lot of AFNetworking 2.0 JSON examples and sending JSON Post request but I can seem to find much for version 1.0 let alone getting the values form a standard post request. Any ideas or resources?

All you should need is to change your code to register a AFJSONRequestOperation instead of AFHTTPRequestOperation.

[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

Then you can use this method on AFHTTPClent to create the operation which will actually be of type AFJSONRequestOperation.

AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:nil failure:nil];
[httpClient enqueueOperation:operation];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM