2014-07-02 70 views
2

我試圖使用AFNetworking庫發送POST請求到像這樣的URL:JSON錯誤AFNetworking

https://m.com/api/2.0/basic/sim_balance.json

這預計是我的參數(URL中的用戶名和密碼作爲NSDictionary)。

的URL給出了一個JSON回來這樣的:

{ 
    "valid_until": "2011-05-05 22:13:28", 
    "sms": 0, 
    "sms_super_on_net_max": 300, 
    "voice_super_on_net": 0, 
    "credits": "0.00", 
    "bundles": [], 
    "is_expired": true, 
    "sms_super_on_net": 0, 
    "voice_super_on_net_max": 3600, 
    "data": 0 
} 

這是我的請求函數:

+(void) request:(NSString *)endpoint : (NSDictionary *) parameters 
    { 
     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
     [manager POST:endpoint parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { 
      NSLog(@"JSON: %@", responseObject); 
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      NSLog(@"Error: %@", error); 
     }]; 
    } 

我總是得到這樣的錯誤:

Error: 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.) UserInfo=0x904b7e0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} 

我驗證了JSON和服務器發送有效的JSON。

有人可以幫我解決這個問題嗎?

+0

你曾經設置過'AFHTTPRequestOperationManager'實例的'requestSerializer'屬性嗎? –

+0

不,我需要這樣做嗎? – user1007522

+0

在您的失敗塊中,嘗試使用'operation.responseString'或'operation.responseData'檢查響應的原始內容。 –

回答

2

我發現解決方案歸功於酯。你也需要設置基本的auth頭文件。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"Tom" password:@"test"]; 
[manager GET:endpoint parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {  
    NSLog(@"JSON: %@", responseObject); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Response data: %@",operation.responseData);  
    NSLog(@"Response String: %@",operation.responseString);  
    NSLog(@"Error: %@", error); 
}]; 
} 
2

要獲得AFHTTPRequestOperationManager連載請求體爲JSON,你需要設置其requestSerializer的價值:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
manager.requestSerializer = [AFJSONRequestSerializer serializer]; 
[manager POST:....]; 

如果不設置requestSerializer屬性,那麼管理對象將通過使用x-www-form-urlencoded系列化默認。

但請注意,AFHTTPRequestOperationManager默認會在響應正文中處理JSON。

+0

我已經添加了這個。但如果它默認情況下發生,爲什麼我需要設置? – user1007522

+0

噢,你說用戶名/密碼可以在請求的URL中發送,所以服務器在請求主體中不期待JSON。我誤解了你的問題。我想你可以不理這個答案。 –

+0

服務器在郵件正文中期待用戶名密碼。 – user1007522