Afnetworking and 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);
}];

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

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]);
}

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];

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<AFMultipartFormData> 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];

AFNetworking - How to make POST request

You can override the default behavior of your request being used with AFNetworking to process as a POST.

NSURLRequest *request = [client requestWithMethod:@"POST" path:path parameters:nil];

This assumes you have overridden the default AFNetworking setup to use a custom client. If you aren't, I would suggest doing it. Just create a custom class to handle your network client for you.

MyAPIClient.h

#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"

@interface MyAPIClient : AFHTTPClient

+(MyAPIClient *)sharedClient;

@end

MyAPIClient.m

@implementation MyAPIClient

+(MyAPIClient *)sharedClient {
static MyAPIClient *_sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:webAddress]];
});
return _sharedClient;
}

-(id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:@"Accept" value:@"application/json"];
self.parameterEncoding = AFJSONParameterEncoding;

return self;

}

Then you should be able to fire off your network calls on the operation queue with no problem.

    MyAPIClient *client = [MyAPIClient sharedClient];
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
[[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];

NSString *path = [NSString stringWithFormat:@"myapipath/?value=%@", value];
NSURLRequest *request = [client requestWithMethod:@"POST" path:path parameters:nil];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// code for successful return goes here
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];

// do something with return data
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// code for failed request goes here
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];

// do something on failure
}];

[operation start];


Related Topics



Leave a reply



Submit