【问题标题】:is there an easy way to get the http status code in the failure block from AFHTTPClient?有没有一种简单的方法可以从 AFHTTPClient 获取失败块中的 http 状态代码?
【发布时间】:2011-12-12 03:02:46
【问题描述】:

我看到有一个可以修改的接受的http状态码列表,但我认为如果我能在失败块中获得http状态码会更简洁..

好的,用操作对象找到答案了

failure:^(AFHTTPRequestOperation *operation, NSError *error){ 
        NSLog(@"error code %d",[operation.response statusCode]);
}];

【问题讨论】:

    标签: afnetworking


    【解决方案1】:

    好的,用操作对象找到答案了

    failure:^(AFHTTPRequestOperation *operation, NSError *error){ 
           NSLog(@"error code %d",[operation.response statusCode]);
    }];
    

    【讨论】:

    • 这可能也有帮助[operation.request HTTPMethod]
    • 我知道这已经过时了,但@wilhelmbot -- HTTPMethod 会给你类似 GET/POST/PUT... 之类的东西,可能对检查响应状态没有帮助。
    【解决方案2】:

    在较新版本的 AFNetworking 中,您可以从错误中检索响应对象:

    [[[error userInfo] objectForKey:AFNetworkingOperationFailingURLResponseErrorKey] statusCode]
    

    如果您正在进一步处理错误并且不想传递响应对象,这很方便。

    【讨论】:

    • 您可能需要先获取底层错误。 NSError *underlyingError = error.userInfo[@"NSUnderlyingError"]
    【解决方案3】:

    对于 AFNetworking 3.0,使用

    failure:^(NSURLSessionTask *operation, NSError *error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)operation.response;
        httpResponse.statusCode;
        NSLog(@"status code: %li", (long)httpResponse.statusCode);
    }
    

    【讨论】:

      【解决方案4】:

      NSInteger operationStatusCode = [operation.error code];

      NSInteger httpStatusCode = operation.response.statusCode;

      如果请求被取消/无法访问/超时,httpStatusCode 将始终为0

      或者,您可以通过了解operationStatusCode 来确定问题。这是一个NSError 对象。

      • 如果无法到达/超时/没有网络来处理请求,operationStatusCode 将是-1009
      • 如果取消操作队列,operationStatusCode 将变为 -999

      您可以在Apple's documentation 中查看所有其他NSError 代码及其描述

      【讨论】:

        【解决方案5】:

        我已经能够使用 Swift 3 获得状态码:

        ((error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey])
            as! HTTPURLResponse).statusCode
        

        【讨论】:

          【解决方案6】:

          这对我有用 在您的请求中添加以下行

          manager.requestSerializer = [AFJSONRequestSerializer 序列化器];

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-04-27
            • 2017-07-05
            • 2011-03-02
            • 2010-09-12
            • 1970-01-01
            • 1970-01-01
            • 2010-10-25
            • 1970-01-01
            相关资源
            最近更新 更多