2012-05-03 57 views
2

我想創建一個POST請求到REST API來發布新的時間條目。該職位要求所需的XML結構如下:AFNetworking - 向REST服務發送XML POST請求?如何形成NSDictionary參數?

<time-entry> 
    <person-id>#{person-id}</person-id> 
    <date>#{date}</date> 
    <hours>#{hours}</hours> 
    <description>#{description}</description> 
</time-entry> 

隨着AFNetworking是XML編碼在幕後做了剛路過一個NSDictionary參數的POST請求?這是我到目前爲止的代碼:

從我APIClient:

-(void)postTimeEntry:(TLActiveWork *)work { 

[self setAuthorizationHeaderWithUsername:[self.activeUser username] 
    password:[self.activeUser password]]; 

// Most of the following is static data. Just trying to get a successful POST at the 
// moment. 
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: 
         [NSString stringWithFormat:@"%@",[[self activeUser] personId]], @"person-id", 
         [NSString stringWithFormat:@"%@",[NSDate date]], @"date", 
         @"1", @"hours", 
         @"testing...!", @"description", 
         nil]; 

NSDictionary *wrapper = [NSDictionary dictionaryWithObjectsAndKeys: 
         params, @"time-entry", 
         nil]; 

NSLog(@"Params: %@", wrapper); 

// AFNetworking call! 

[self postPath:[NSString stringWithFormat:@"/projects/%@/time_entries.xml", 
    [[work project] projectId]] parameters:wrapper 
    success:^(AFHTTPRequestOperation *operation, id responseObject) { 

    NSLog(@"-----SUCCESS!!!-----"); 

} failure:^(__unused AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"failure: %ld - %@", [operation.response statusCode], 
      [error description]); 
}]; 
} 

是。

[self registerHTTPOperationClass:[AFXMLRequestOperation class]]; 

每次我試圖用這個代碼,我總是得到一個422響應代碼失敗,我相信是指通過實體是不能處理的,以發帖時間現在:我APIClient操作(一個或多個)通過配置XML。 https://stackoverflow.com/a/3291292/312411

我想我的問題僅僅是這一職位的XML沒有被正確建立通過NSDictionary的PARAMS參數傳遞?

任何幫助將大大讚賞!

謝謝。

回答

0

雖然我的答案是不及時,我希望它能幫助其他人遇到此問題。下面是如何讓使用AFNetworkingXML POST請求的示例。

AFHTTPClient *HTTPClient = [[AFHTTPClient alloc] initWithBaseURL:@"https://stackoverflow.com"]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:HTTPClient.baseURL]; 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:[[NSFileManager defaultManager] contentsAtPath:[[NSBundle mainBundle] pathForResource:@"TheNameOfTheXMLFileToSend" ofType:@"xml"]]; 

AFHTTPRequestOperation *operation = [HTTPClient HTTPRequestOperationWithRequest:request 
success:^(AFHTTPRequestOperation *operation, id responseObject) 
{ 
    // The server responded without an error. 
} 
failure:^(AFHTTPRequestOperation *operation, NSError *error) 
{ 
    // The server responded with an error. 
}]; 

[HTTPClient enqueueHTTPRequestOperation:operation];