通过AFHTTPClient调用接收错误响应

时间:2012-06-07 20:49:16

标签: json afnetworking

我正在按照文档中的建议将AFHTTPClient实现为单例类,并在帖子中使用JSON数据调用它,并接收JSON数据:

[[BMNetworkCalls sharedInstance] postPath:theURL parameters:theDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"my return is: %@", [responseObject valueForKeyPath:@"Result"]);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {            
    NSLog(@"error in network call: %@", [error localizedDescription]);
}];

一切都很好,但是如果我收到错误,(“HTTPRequestOperation中的错误:预期状态代码在(200-299),得到400”),我实际上想要来读取responseObject这里也是(这是我使用的API的方式告诉我我引起了什么类错误。)

我可以使用AFJSONRequestOperation:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"my return is: %@", [JSON valueForKeyPath:@"Result"]);

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"exception code: %@", [JSON valueForKeyPath:@"ExceptionCode"]);
    NSLog(@"exception message: %@", [JSON valueForKeyPath:@"ExceptionMessage"]);
}];
[operation start];

我怎样才能(我可以?)使用AFHTTPClient来做这件事吗?

2 个答案:

答案 0 :(得分:1)

operation变量包含您需要的所有内容:

[[BMNetworkCalls sharedInstance] postPath:theURL parameters:theDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
  // ...
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    if ([operation isKindOfClass:[AFJSONRequestOperation class]]) {
      id JSON = [(AFJSONRequestOperation *)operation responseJSON];
      NSLog(@"JSON: %@", JSON)
    }
}];

答案 1 :(得分:-1)

所有的归功于@ phix23,他指出了我正确的方向!

这是我在子类AFHTTPClient中编写的自定义方法,它允许我在收到400错误后看到JSON响应:

- (void) myPostPath:(NSString *)path
        parameters:(NSDictionary *)parameters
           success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 
           failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
{
    NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];   
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:success failure:failure];
    [self enqueueHTTPRequestOperation:operation];
}

我叫它:

[[BMNetworkCalls sharedInstance] myPostPath:theURL parameters:theDict success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
    NSLog(@"my return is: %@", [responseObject valueForKeyPath:@"Result"]);

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {          
    NSLog(@"exception code: %@", [JSON valueForKeyPath:@"ExceptionCode"]);
}];