AFNetworking:从 Http 响应中获取 JSON 值
Posted
技术标签:
【中文标题】AFNetworking:从 Http 响应中获取 JSON 值【英文标题】:AFNetworking: Get JSON Value From Http Response 【发布时间】:2014-07-09 23:02:38 【问题描述】:我主要是一名 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 请求中获取值了。 有什么想法或资源吗?
【问题讨论】:
您是否在NSLog
行遇到异常,您实际上并没有说出问题所在...
【参考方案1】:
您只需更改代码以注册 AFJSONRequestOperation 而不是 AFHTTPRequestOperation。
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
然后您可以在 AFHTTPClent 上使用此方法来创建实际类型为 AFJSONRequestOperation 的操作。
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:nil failure:nil];
[httpClient enqueueOperation:operation];
【讨论】:
以上是关于AFNetworking:从 Http 响应中获取 JSON 值的主要内容,如果未能解决你的问题,请参考以下文章
AFNetworking:无法从 AFHTTPRequestOperation 获取响应字符串
通过 AFNetworking 从服务器获取 Json 响应