AFNetworking - How to specify multiple values for

2019-06-21 04:31发布

问题:

I am trying to pass multiple values for one parameter key to an HTTP request using the AFHTTPClient method "postPath". However, the parameters variable is an NSDictionary so I can not set multiple values for my key "email". I've tried sending the e-mail values as a comma separated string but that does not work as my server returns an error saying I have not specified any e-mail value.

I did read in the documentation about using multipartFormRequestWithMethod method but I could not completely figure out how to make this work. Can anyone provide an example of using this method with multiple values for a single key?

Thanks

Rich

回答1:

Combining the multi query values for one key.

If you use NSDictionary + NSSet you get query url without [] from NSArray.

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[NSSet setWithObjects:@"value1", @"value2", nil], @"myKey", nil];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSURLRequest *request = [httpClient requestWithMethod:@"GET" path:@"/path" parameters:params];

PS: Better late than never...



回答2:

Combining the multi values for the one key.

using NSDictionary + NSArray

For example:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: @"value1", @"param1", @"value2", @"param2", [NSArray arrayWithObjects:@"value3",@"value4",@"value5",nil], @"param3", nil];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/yourhostpath" parameters:params];

you need to replace "url" and "yourhostpath" to your own, please reference AFHttpClient demo code of AFNetworking for this.



回答3:

You cannot define multiple values for a single key. However, you can define a key to have an array, which itself contains multiple values.

That said, it doesn't seem like email would be a field that should have multiple definitions. If you do want to accept multiple values, you should probably rename that parameter to emails.