Migrating ASIHTTPRequest to AFNetworking (submit to a URL with POST variables)
For my third and final AFNetworking migration series of posts, let us consider calling a web service URL with POST variables.
Here was the ASIHTTPRequest code:
NSMutableString *fileURL = [NSMutableString stringWithString:THE_URL];
NSURL *url = [NSURL URLWithString:fileURL];
__block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request addRequestHeader:@"Content-Type" value:@"application/json; charset=utf-8"];
[request setRequestMethod:@"POST"];
[request setPostValue:theID forKey:@"id"];
[request setCompletionBlock:^{
NSLog(@"success with response string %@", request.responseString);
}];
[request setFailedBlock:^{
NSLog(@"error: %@", request.error.localizedDescription);
}];
[request startAsynchronous];
And here is the corresponding AFNetworking code:
NSMutableString *fileURL = [NSMutableString stringWithString:THE_URL];
AFHTTPClient *client = [[[AFHTTPClient alloc] initWithBaseURL:url] autorelease];
NSDictionary *params = @ { @"id" : theID };
NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:fileURL parameters:params];
AFHTTPRequestOperation *op = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"success with response string %@", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", error.localizedDescription);
}];
[op start];
BTW, Happy Valentine’s Day to one and all.