如何在 iOS 中发出 POST 请求?

Posted

技术标签:

【中文标题】如何在 iOS 中发出 POST 请求?【英文标题】:How to make a POST request in iOS? 【发布时间】:2014-04-17 03:15:06 【问题描述】:

我正在尝试弄清楚如何使用 AFNetworking 2.0。我正在尝试使用用户名和密码发布登录信息。

这是我当前的尝试,但由于未发送某些内容而无法正常工作。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @@"loginName": @"password";
[manager POST:@"http://xxxx.com/login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) 
    NSLog(@"JSON: %@", responseObject);



    NSLog(@"Data saved");

    MainViewController *mainView = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
    mainView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController: mainView animated:YES completion:nil];


 failure:^(AFHTTPRequestOperation *operation, NSError *error) 
    NSLog(@"Error: %@", error);
    NSString *error_msg = (NSString *) error;
    [self alertStatus:error_msg :@"Sign in Failed!" :0];
];

    
 @catch (NSException * e) 
         NSLog(@"Exception: %@", e);
         [self alertStatus:@"Sign in Failed." :@"Error!" :0];
    

但是什么都没有发生,请继续获取此打印输出:

2014-04-16 20:14:09.903 Slidedrawer[9279:60b] Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8e78bd0 NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.

响应将采用 JSON 格式。有人知道我需要在代码中编辑什么或如何修复它吗?

JSON: 
    "_id" = 533cb1c453769a02008c2d55;
    name = dddd;
    picture = "/img/users/default.jpg";

如何访问上面返回的 JSON,尝试将每个返回的属性分解为字符串或整数等...

【问题讨论】:

【参考方案1】:

试试这个:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @@"userName": username, @"password": password;
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format
[manager POST:@"http://asd.com/login.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) 
    NSLog(@"%@", responseObject);
 failure:^(AFHTTPRequestOperation *operation, NSError *error) 
    NSLog(@"%@", error);
];

要解析响应,请使用 responseObject 作为 NSDictionary

NSString *userName = [responseObject objectForKey:@"userName"];
NSString *password = [responseObject objectForKey:@"password"];

希望这会有所帮助.. :)

【讨论】:

嘿,我看到了 responseSerializer,如果它以我上面发布的方式返回,我该如何准确地从中提取数据? @lion789 > 欢迎。 :)【参考方案2】:

您可以找到Send Nested JSON using AFNetworking 的答案。

错误 错误域=NSCocoaErrorDomain Code=3840 从服务器接收到无效的 JSON 对象。这可能是由于服务器对您丢失的参数处理不当造成的。您的参数字典只有一个键对象 loginName。

【讨论】:

以上是关于如何在 iOS 中发出 POST 请求?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 AFNetworking 在 iOS 目标 c 中发出此帖子请求

如何使用 Python requests 库发出 post 请求?

如何在 Swift 中发出 NSURLSession POST 请求

如何在 robobrowser-python 中发出 POST 请求

如何在反应中使用 axios 发出 POST 请求?

如何使用javascript发出post请求