Afnetworking Post Request

AFNetworking Post Request

It's first worth adding (as this answer is still popular 6 years after I initially wrote it...) that the first thing you should consider is whether you should even use AFNetworking. NSURLSession was added in iOS 7 and means you don't need to use AFNetworking in many cases - and one less third party library is always a good thing.

For AFNetworking 3.0:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

For AFNetworking 2.0 (and also using the new NSDictionary syntax):

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

If you are stuck using AFNetworking 1.0, you need to do it this way:

NSURL *url = [NSURL URLWithString:@"https://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
[httpClient postPath:@"/myobject" 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);
}];

afnetworking 3.0 Migration: how to POST with headers and HTTP Body

I was able to figure this out myself.

Here's the solution.

First, you need to create the NSMutableURLRequest from AFJSONRequestSerializer first where you can set the method type to POST.

On this request, you get to setHTTPBody after you have set your HTTPHeaderFields. Make sure to set the body after you have set the Header fields for content-type, or else the api will give a 400 error.

Then on the manager create a dataTaskWithRequest using the above NSMutableURLRequest. Don't forget to resume the dataTask at the very end or else nothing will get sent yet. Here's my solution code, hopefully someone gets to use this successfully:

NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] 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:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];


[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {

if (!error) {
NSLog(@"Reply JSON: %@", responseObject);

if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(@"Error: %@, %@, %@", error, response, responseObject);
}
}] resume];

How to add headers in AFNetworking 4.0 in POST Request?

From the Above Given Answers I found a midway for the answers. Thanks for the Response @baiyidjp and @Silversky Technology

     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];

NSString *path=[[NSString alloc]initWithFormat:@"%@",URL];

NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
[parameter setValue:@"123456" forKey:@"id"];

NSDictionary *headers = @{@"Authorization":[NSString stringWithFormat:@"Bearer %@",[defaults valueForKey:@"ApiToken"]]};

[manager POST:[NSURL URLWithString:path].absoluteString parameters:parameter headers:headers progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(@"Response Object response is....==%@",responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(@"Error Last 2 Done: %@", [error localizedDescription]);
}

In AFNetworking, difference between httpbody and parameter post request?

The first method is intended for situations where you are passing a single blob of raw data to the server. Use this for:

  • Sending a blob of JSON data to a CGI that expects JSON data
  • Sending pre-encoded body data in URL-encoded or form-data-encoded format
  • The file data in a PUT request sent to a server that supports WebDAV.

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. :-)

send JSON object in POST request AFNetworking , iOS

@interface AFJSONRequestSerializer : AFHTTPRequestSerializer

AFJSONRequestSerializeris a subclass ofAFHTTPRequestSerializerthat encodes parameters as JSON using NSJSONSerialization.

add this AFJSONRequestSerializer is used for send JSON not a Raw Data add this and try once

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

e.g

NSString *string = [NSString stringWithFormat:@"%@?post_user_info",BaseURLString];
NSString *escapedPath = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

/************** karthik Code added ******************/
AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
/************** karthik Code added ******************/

NSDictionary *params = @{@"1": @"hello world",
@"2": @"my@you.com",
@"3": @"newworldorder"};
[manager POST:escapedPath parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
NSLog(@"%@",responseObject);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
NSLog(@"json == %@", json);

} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];

Update Params

NSDictionary *params = @{@"1": @"hello world",
@"2": @"my@you.com",
@"3": @"newworldorder"};
NSMutableDictionary *modify = [NSMutableDictionary new];
[modify setObject:params forKey:@"input_values"];

you get output of

Sample Image

AFNetworking 3.x post request with data and image

Use this code to post an image using AFNetworking:

AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSMutableDictionary *paramDict = [NSMutableDictionary new]; // Add additional parameters here
AFHTTPRequestOperation *op = [manager POST:UPDATE_PROFILE_IMAGE parameters:paramDict constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFileData:imageData name:@"file" fileName:@"filename" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
// Success
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Failure
}];
[op start];


Related Topics



Leave a reply



Submit