2013-05-30 141 views
2

试图将我的代码从ASIHttpRequest迁移到AFNetworking。似乎有类似的问题,但couldnt找到解决我的问题。AFNetworking在(200-299)中的预期状态码,得到403

我的代码与ASIHttpRquest正常工作。

我发送一个简单的发布请求到我的服务器并监听http响应。如果http response是200一切正常,但如果我发送另一个状态代码> 400 AFNetworking块失败。

服务器端的响应:

$rc = $stmt->fetch(); 
    if (!$rc) { 
    // echo "no such record\n"; 
     $isrecordExist=0; //false does not exists 
     sendResponse(403, 'Login Failed'); 
     return false; 
    } 
    else { 
    // echo 'result: ', $result, "\n"; 
     $sendarray = array(
      "user_id" => $result, 
     ); 
     sendResponse(200, json_encode($sendarray)); 
    } 

IOS部分:

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: 
          [NSURL URLWithString:server]]; 
    client.allowsInvalidSSLCertificate=YES; 

    [client postPath:loginForSavingCredientials parameters:params success:^(AFHTTPRequestOperation *operation, id response) { 
    if (operation.response.statusCode == 500) {} 
    else if (operation.response.statusCode == 403) {} 
    else if (operation.response.statusCode == 200) {//able to get results here   NSError* error; 
     NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
     NSDictionary* json =  [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] 
                   options: NSJSONReadingMutableContainers 
                    error: &error];} 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"failure %@", [error localizedDescription]); 
    }]; 

的NSLog:

failure Expected status code in (200-299), got 403 

我该如何解决这个问题?

回答

12

AFNetworking获得2xx(成功)状态码时,它调用成功块。

当它得到4xx(客户端错误)或5xx(服务器错误)状态码时,它会调用故障块,因为出现了问题。

因此,您只需将500或403状态码的检查移至故障块即可。

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:server]]; 
client.allowsInvalidSSLCertificate=YES; 

[client postPath:loginForSavingCredientials parameters:params success:^(AFHTTPRequestOperation *operation, id response) { 
    if (operation.response.statusCode == 200) {//able to get results here   NSError* error; 
     NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
     NSDictionary* json = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] 
                  options: NSJSONReadingMutableContainers 
                   error: &error]; 
    } 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"failure %@", [error localizedDescription]); 
    if (operation.response.statusCode == 500) {} 
    else if (operation.response.statusCode == 403) {} 
}]; 
1

当您创建请求操作时,您需要告诉它哪些响应状态码可以接受(意味着成功)。默认情况下,这是在范围200码 - > 299

设置开始使用客户端之前:

AFHTTPRequestOperation.acceptableStatusCodes = ...; 

[client postPath: 

文档是here

相关问题