【问题标题】:Adding parameters to request with AFNetworking使用 AFNetworking 向请求添加参数
【发布时间】:2013-05-17 14:40:09
【问题描述】:

我最近关注了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 的文档,但没有从那里得到任何有用的信息。

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

【问题讨论】:

    标签: ios afnetworking


    【解决方案1】:

    您可以使用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 正文中,而不是在 ? 之后网址。

      【讨论】:

      • 是的,HTTPClient幕后的requestWithMethod:path:parameters:
      猜你喜欢
      • 2013-10-28
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2015-07-21
      相关资源
      最近更新 更多