AFNetworking 2.0 AFHTTPSessionManager: how to get status code and response JSON in failure block?

后端 未结 7 804
你的背包
你的背包 2020-12-04 10:08

When switched to AFNetworking 2.0 the AFHTTPClient has been replaced by AFHTTPRequestOperationManager / AFHTTPSessionManager (as mentioned in the migration guide). The very

相关标签:
7条回答
  • 2020-12-04 10:54

    There is another approach besides the accepted answer.

    AFNetworking is calling your failure block, sans any response object, because it believes a true failure has occurred (e.g. a HTTP 404 response, perhaps). The reason it interprets 404 as an error is because 404 isn't in the set of "acceptable status codes" owned by the response serializer (the default range of acceptable codes is 200-299). If you add 404 (or 400, or 500, or whatever) to that set then a response with that code will be deemed acceptable and will be routed to your success block instead - complete with the decoded response object.

    But 404 is an error! I want my failure block to be called for errors! If that's the case then use the solution referred to by the accepted answer: https://github.com/AFNetworking/AFNetworking/issues/1397. But consider that perhaps a 404 is really a success if you're going to be extracting and processing the content. In this case your failure block handles real failures - e.g. unresolvable domains, network timeouts, etc. You can easily retrieve the status code in your success block and process accordingly.

    Now I understand - it might be super nice if AFNetworking passed any responseObject to the failure block. But it doesn't.

        _sm = [[AFHTTPSessionManager alloc] initWithBaseURL: [NSURL URLWithString: @"http://www.stackoverflow.com" ]];
    
        _sm.responseSerializer = [AFHTTPResponseSerializer new];
        _sm.responseSerializer.acceptableContentTypes = nil;
    
        NSMutableIndexSet* codes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(200, 100)];
        [codes addIndex: 404];
    
    
        _sm.responseSerializer.acceptableStatusCodes = codes;
    
        [_sm GET: @"doesnt_exist"
      parameters: nil success:^(NSURLSessionDataTask *task, id responseObject) {
    
          NSHTTPURLResponse* r = (NSHTTPURLResponse*)task.response;
    
          NSLog( @"success: %d", r.statusCode );
    
          NSString* s = [[NSString alloc] initWithData: responseObject encoding:NSUTF8StringEncoding];
    
          NSLog( @"%@", s );
    
      }
         failure:^(NSURLSessionDataTask *task, NSError *error) {
    
             NSLog( @"fail: %@", error );
    
    
         }];
    
    0 讨论(0)
提交回复
热议问题