0

我正在使用 AFNetworking 从服务器获取 JSON。我的问题是,如果会话过期,服务器会回复字符串“NOSESSION”。

这是我的代码:

[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request


                                  success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){


                                      NSArray *jsonArray =[JSON valueForKey:@"posts"];

                                        //DOING SOMETHING WITH jsonArray
                                        // in case that the response is NOSESSION do something                                        



                                  }

                                  failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){




                                       }];

[operation start];

我的问题是这是请求失败,因为响应不是字符串。错误信息:

Failed Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)

有没有办法知道响应字符串?(我不介意在失败中捕获它我只想知道会话何时过期)

4

1 回答 1

0

你可以检查你的 NSHTTPURLResponse 的 statusCode。当你的服务器遇到这样的错误时,他通常会返回一个 statusCode。

示例: 403:禁止 404:找不到页面 500:内部服务器错误。

您可以检查 HTTP statusCode 是否在 200 和 400 之间。==> 没有错误

if(response.statusCode < 400 && response.statusCode > 200) {
    // do normal stuff 
} else {
    // handle error
}

您可以在此处找到有关 HTTP statusCodes 的更多信息: http ://en.wikipedia.org/wiki/List_of_HTTP_status_codes

于 2013-09-05T18:13:02.030 回答