如何在Afnetworking post方法中将数组作为参数发送?

时间:2013-07-16 05:29:04

标签: ios ios6 afnetworking

嗨我需要发送一个数组作为Afnetworking Query String

中的一个参数
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL    URLWithString:@"http://192.008.0.28/aaa/a/"]];

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: @"20", @"Miles", [NSArray arrayWithObjects:@"1",@"2",@"3",nil], @"Interval", nil];

    [httpClient postPath:iUpdateNotificationMethod parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"Request Successful, response '%@'", responseStr);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
    }];

但是服务器端我们得到了“Miles”:20,“Intervals”:null如何修复它 谢谢,

3 个答案:

答案 0 :(得分:2)

试试这个

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:OAuthBaseURL];

NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithCapacity:0];
    for (int i =0; i < [userIDs count]; i++) {
        NSString *userID = [[userIDs objectAtIndex:i] objectForKey:@"id"];
        NSDictionary *tmpDict = [NSDictionary dictionaryWithObjectsAndKeys:userID , [NSString stringWithFormat:@"ids[%i]",i], nil];
        [parameters addEntriesFromDictionary:tmpDict];
    }
    [client postPath:@"/user"
          parameters:parameters
             success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSData *data = (NSData *)responseObject;
                NSString *jsonStr = [[NSString alloc] initWithData:data
                                                          encoding:NSUTF8StringEncoding];
                NSLog(@"jsonStr %@",jsonStr);

            }
            failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self showError];
            }
     ];

答案 1 :(得分:0)

由于您正在提交数组,因此AFNetworking会生成不同的参数名称,并使用您提供的值重载它。例如,您的请求会生成以下查询字符串:

Interval[]=1&Interval[]=2&Interval[]=3&Miles=20

这是在AFHTTPClient.m函数的AFQueryStringPairsFromKeyAndValue中定义的。

如果您想保留原始参数,则应自行决定如何将NSArray转换为NSString。例如,您可以执行[myArray componentsJoinedByString:@","]之类的操作,然后将其拆分回服务器上的元素。如果选择此方法,请注意使用可能出现在实际数据中的字符。

答案 2 :(得分:-1)

我相信这会奏效:     params = @ {@“Miles”:@“20”,@“Interval”:@ [@“1”,@“2”,@“3”]};