2012-03-29 80 views
8

簡介背景故事,我們以前的開發人員使用ASIHTTPRequest來發出POST請求並從我們的web服務中檢索數據。原因未知我們的應用程序的這部分停止工作。似乎有足夠的時間來證明未來,並與AFNetworking合作。 REST webservice在CakePHP框架上運行。AFNetworking POST到REST webservice

總之,我沒有收到使用AFNetworking的請求響應字符串。

我知道web服務工作,因爲我能夠成功發佈的數據,並使用得到適當的響應捲曲: 捲曲-d「數據[產品型號] [field0] = field0value &數據[產品型號] [字段1] = field1value」 https://example.com/api/class/function.plist

根據以前的開發人員的指示,我想出了以下內容。

#import "AFHTTPRequestOperation.h"  

… 

- (IBAction)loginButtonPressed { 

    NSURL *url = [NSURL URLWithString:@"https://example.com/api/class/function.plist"]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

    [request setHTTPMethod:@"POST"]; 

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

    [request setValue:[usernameTextField text] forHTTPHeaderField:@"data[User][email]"]; 

    [request setValue:[passwordTextField text] forHTTPHeaderField:@"data[User][password]"]; 

    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

     NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]); 

     NSLog(@"response string: %@ ", operation.responseString); 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

     NSLog(@"error: %@", operation.responseString); 

    }]; 

    [operation start]; 

} 

輸出: 操作hasAcceptableStatusCode:200 響應字符串:空白plist文件

嘗試的解決方案1: AFNetworking Post Request 所提出的解決方案使用AFHTTPRequestOperation的函數調用operationWithRequest。但是,當我嘗試使用所述解決方案時,我收到警告「類方法」+ operationWithRequest:完成:'未找到(返回類型默認爲'id'「

嘗試解決方案2:NSURLConnection。output:打印傳遞消息的成功日誌,但不響應字符串 *更新 - 。返回空白的plist

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; 
NSString *httpBodyData = @"data[User][email][email protected]&data[User][password]=awesomepassword"; 
[httpBodyData dataUsingEncoding:NSUTF8StringEncoding]; 
[req setHTTPMethod:@"POST"]; 
[req setHTTPBody:[NSData dataWithContentsOfFile:httpBodyData]]; 
NSHTTPURLResponse __autoreleasing *response; 
NSError __autoreleasing *error; 
[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error]; 

// *update - returns blank plist 
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil]; 
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
NSLog(@"responseData %@",str); 

if (error == nil && response.statusCode == 200) { 
    // Process response 
    NSLog(@"success");//returns success code of 200 but blank 
    NSLog(@"resp %@", response); 
} else { 
    // Process error 
    NSLog(@"error"); 
} 
+0

你好,Pouria,你嘗試使用NSURLConnection發送同步請求嗎? – 8vius 2012-03-29 15:17:14

+0

嘗試解決方案2:我是如何嘗試NSURLConnection。 – Airuop 2012-03-29 17:20:56

+0

服務器端的所有設置是否正確?像擴展解析一樣,響應的佈局和它們的視圖?看起來更像是一個服務器問題,而不是客戶端問題。 – 8vius 2012-03-29 19:08:18

回答

18

這些是最終滿足我對Web服務請求的基本要求(剝離條件是我爲自己使用的)。感謝@ 8vius和@mattt的建議!

- (IBAction)loginButtonPressed {   
    NSURL *baseURL = [NSURL URLWithString:@"https://www.example.com/api/class"]; 

    //build normal NSMutableURLRequest objects 
    //make sure to setHTTPMethod to "POST". 
    //from https://github.com/AFNetworking/AFNetworking 
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL]; 
    [httpClient defaultValueForHeader:@"Accept"]; 

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: 
          [usernameTextField text], kUsernameField, 
          [passwordTextField text], kPasswordField, 
          nil]; 

    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" 
      path:@"https://www.example.com/api/class/function" parameters:params]; 

    //Add your request object to an AFHTTPRequestOperation 
    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] 
             initWithRequest:request] autorelease]; 

    //"Why don't I get JSON/XML/Property List in my HTTP client callbacks?" 
    //see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ 
    //mattt's suggestion http://stackoverflow.com/a/9931815/1004227 - 
    //-still didn't prevent me from receiving plist data 
    //[httpClient registerHTTPOperationClass: 
    //   [AFPropertyListParameterEncoding class]]; 

    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]]; 

    [operation setCompletionBlockWithSuccess: 
     ^(AFHTTPRequestOperation *operation, 
     id responseObject) { 
     NSString *response = [operation responseString]; 
     NSLog(@"response: [%@]",response); 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"error: %@", [operation error]); 
    }]; 

    //call start on your request operation 
    [operation start]; 
    [httpClient release]; 
} 
+0

註冊plist操作隻影響使用'AFHTTPClient -HTTPRequestOperationWithRequest:success:failure:'創建的請求操作。 'alloc init'' AFHTTPRequestOperation'總是會給你一個'AFHTTPRequestOperation'。 – mattt 2012-04-05 05:00:13

+0

謝謝,@mattt! – Airuop 2012-04-09 14:04:17

+0

@pouria,這裏是什麼路徑。它是否像一個相同的URL。請幫我,我被困在路徑。 – 2013-07-05 10:55:17

6

使用AFHTTPClient -postPath:parameters:success:failure:,通過你的參數(嵌套詞典/陣列罰款)如果你希望一個plist中回來。 ,一定要有客戶端註冊AFPropertyListRequestOperation

在任何情況下,setValue:forHTTPHeaderField:不是你想要的。 HTTP headers用於指定關於請求本身的信息;數據是請求主體的一部分。 AFHTTPClient自動將參數轉換爲GET請求的查詢字符串或POST等的HTTP主體。

+0

我解決了這個問題,但我有一種感覺,我仍然在做錯誤或效率低下的事情。如果您快速查看我的解決方案,我將不勝感激。謝謝! – Airuop 2012-04-03 21:11:21