使用AFNetworking添加要求的参数

时间:2013-05-17 14:40:09

标签: ios afnetworking

我最近关注了CodeSchool course to learn iOS,他们建议使用AFNetworking与服务器进行互动。

我正在尝试从我的服务器获取JSON,但我需要将一些参数传递给url。我不希望将这些参数添加到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的文档,但从那里得不到任何有用的东西。

如何将用户名和密码传递给此请求以在服务器中读取?

2 个答案:

答案 0 :(得分: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:方法,而不是手动创建操作并启动它。

答案 1 :(得分: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正文中而不是{{1}之后URL中的1}}。