ios - 使用 AFNetworking 向请求添加参数

标签 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 的文档但没有从那里得到任何有用的东西。

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

最佳答案

您可以使用 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: 方法,而不是手动创建操作并启动它。

关于ios - 使用 AFNetworking 向请求添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16611775/

相关文章:

ios - 如何将自定义 header 添加到 AFNetworking 上传任务?

ios - 如何将AFHTTPClient,Afnetworking 1.0迁移到2.0

iphone - 调试 AFNetworking 内存使用峰值

ios - 我如何知道在 AFNetworking 中是否执行了成功或失败 block

afnetworking - AFNetworking 2.0 中的 setTaskDidReceiveAuthenticationChallengeBlock

iOS 静默推送通知仅在连接到 xcode 时有效

ios - Self.Type 不能在 swift 中直接转换为 AnyClass 以扩展到 objective-c 类

ios - 同一个对象哈希不同,Swift,Hashable

ios - Swift - 在单击按钮之前无法重命名按钮

iphone - NSURLConnection 在服务器上发送数据两次