gpt4 book ai didi

ios - AFNetworking:从 Http 响应中获取 JSON 值

转载 作者:行者123 更新时间:2023-11-29 12:41:55 26 4
gpt4 key购买 nike

我主要是一名 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 suit 看起来像这样的 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];

关于ios - AFNetworking:从 Http 响应中获取 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com