AFNetworking Overload a Post Parameter

I am switching from ASIHTTPRequest to AFNetworking and am facing a problem.

I'm trying to get into the API with a request that overloads the post parameter. I previously used ASIFormDataRequest for this and used this code to update 3 IDs at the same time.

// ASIHTTPRequestCode
[request addPostValue:@"value1" forKey:@"id"];
[request addPostValue:@"value2" forKey:@"id"];
[request addPostValue:@"value3" forKey:@"id"];


Since AFNetworking uses NSDictionary to store key value pairs, it doesn't seem straightforward how to do it. Any ideas?


source to share

3 answers

I can't immediately see a direct way to do this using AFNetworking, but it can be done.

If you look at the code for AFHTTPClient requestWithMethod

, you will see this line, which sets the request body to contain the parameters:

 [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding) dataUsingEncoding:self.stringEncoding]];


Basically, you can pass an empty dictionary in requestWithMethod

for parameters, then it returns, call it request setHTTPBody

yourself, composing the query string yourself, similar to how it does AFQueryStringFromParametersWithEncoding




You can create a request like this:

NSURL *url = [NSURL URLWithString:@""];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *postValues = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@,%@,%@",@"value1",@"value2",@"value3"] forKey:@"id"];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/path/to/your/page.php" postValues];




I ran into a similar problem but solved it by updating the url. I added parameters that I need to send using url and set "parameters to nil"

so the url became something like



and sent nil as paramDictionary

[request setHTTPBody:[AFQueryStringFromParametersWithEncoding(nil, self.stringEncoding) dataUsingEncoding:self.stringEncoding]];




All Articles