First with httpbody:
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"url" parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPBody:da];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"Reply JSON: %@", responseObject);
} else {
NSLog(@"Error: %@, %@, %@", error, response, responseObject);
}
}] resume];
Second with parameter:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager POST:@"https://exmaple.com/post.php" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", error);
}];
What is the different between this two post method? I notice one different is parameter one will use url encoding method to encode data while the other will pass the raw data.
The first method is intended for situations where you are passing a single blob of raw data to the server. Use this for:
The second method (providing a series of parameters) is intended to emulate form submission by providing the body data as a series of URL-encoded key-value pairs. For most non-JSON-based CGI work, this is the one you want.
The decision of which one to use is largely determined by what happens on the server side. If the script expects the body data to be a blob of JSON, encode the JSON data to an NSData object and send it as the body data. If the script expects the results of an HTML form, use the other approach. If the script doesn't care, use whichever approach sends less data on average. :-)