2013-05-30 143 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

相關問題