2013-05-17 108 views
5

我最近遵循CodeSchool course to learn iOS,他們推薦使用AFNetworking與服務器交互。通過AFNetworking添加參數請求

我想從我的服務器得到一個JSON,但我需要傳遞一些參數到網址。我不希望將這些參數添加到URL中,因爲它們包含用戶密碼。

對於一個簡單的URL請求,我有以下代碼:

NSURL *url = [[NSURL alloc] initWithString:@"http://myserver.com/usersignin"]; 
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; 

AFJSONRequestOperation *operation = [AFJSONRequestOperation 
     JSONRequestOperationWithRequest:request 
       success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
         NSLog(@"%@",JSON); 
       } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
         NSLog(@"NSError: %@",error.localizedDescription);    
       }]; 

[operation start]; 

我已經檢查的NSURLRequest的文檔,但並沒有從那裏得到任何有用的東西。

我應該如何傳遞用戶名和密碼到這個請求在服務器中讀取?

回答

6

您可以使用AFHTTPClient

NSURL *url = [[NSURL alloc] initWithString:@"http://myserver.com/"]; 
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url]; 

NSURLRequest *request = [client requestWithMethod:@"POST" path:@"usersignin" parameters:@{"key":@"value"}]; 

AFJSONRequestOperation *operation = [AFJSONRequestOperation 
    JSONRequestOperationWithRequest:request 
      success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
        NSLog(@"%@",JSON); 
      } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
        NSLog(@"NSError: %@",error.localizedDescription);    
      }]; 

[operation start]; 

理想情況下,你會繼承AFHTTPClient並利用其postPath:parameters:success:failure:方法,而不是手動創建的操作和啓動它。

2

您可以在一個的NSURLRequest設置POST參數是這樣的:

NSString *username = @"theusername"; 
NSString *password = @"thepassword"; 

[request setHTTPMethod:@"POST"]; 
NSString *usernameEncoded = [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSString *passwordEncoded = [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

NSString *postString = [NSString stringWithFormat:[@"username=%@&password=%@", usernameEncoded, passwordEncoded]; 
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 

換句話說,您創建一個查詢字符串,如果你是在URL中傳遞的參數相同,但設置方法POST並將該字符串放在HTTP正文中,而不是在URL中的?之後。

+0

是的,在HTTPClient ** requestWithMethod的場景後面:path:parameters:** – onmyway133