繁体   English   中英

AFNetworking:从Http响应获取JSON值

[英]AFNetworking: Get JSON Value From Http Response

我主要是一名Android开发人员,并且是IOS的新手。 我正在使用AFNetworking 1.0,因为我正在使用现有资源,并且正在发送标准的http Post请求并返回数据,如下所示:

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

根据burp西装,响应中应包含如下所示的JSON数据:

{"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"}.

如何获取这些JSON值? 我已经看过很多AFNetworking 2.0 JSON示例和发送JSON Post请求,但是我似乎可以在1.0版中找到很多东西,更不用说从标准post请求中获取值了。 有什么想法或资源吗?

您需要做的就是更改代码以注册AFJSONRequestOperation而不是AFHTTPRequestOperation。

[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

然后,您可以在AFHTTPClent上使用此方法来创建实际上为AFJSONRequestOperation类型的操作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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