Objective-C如何使用AFNetworking发布表单数据?

时间:2015-02-18 12:02:38

标签: ios afnetworking afnetworking-2

我有一个网络服务,我可以通过Postman实用程序成功发布电话。在Postman上,设置为Postman settings

我无法使用代码使用Afnetworking进行相同的调用。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"body": @{@"email":@"email@gmail.com",@"name":@"myName"}};
[manager POST:@"http://myURL.com/user" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

我的猜测是我没有正确设置表单数据?

1 个答案:

答案 0 :(得分:5)

你需要序列化你的params字典,然后对它进行字符串编码,因为你的body参数中有一个JSON对象。 试试这个:

    NSDictionary *params = @{@"email": @"email@gmail.com", @"name": @"myName"};
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
    NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSDictionary *dict = @{@"body":json};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager POST:@"http://myURL.com/user" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSString *myString = [[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding];
        NSLog(@"Error: %@", myString);
    }];