Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST request with JSON body AFNetworking 2.0

Is there anyway to send a POST request with a JSON body using AFNetworking ~> 2.0?

I have tried using:
manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager POST:<url> parameters: @{@"data":@"value"} success: <block> failure: <block>'

but it doesn't work. Any help is greatly appreciated. Thanks

like image 825
Vishesh Joshi Avatar asked Feb 07 '15 00:02

Vishesh Joshi


2 Answers

You can add your JSON body in NSMutableURLRequest not direct in parameters:. See my sample code :

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Set post method
[request setHTTPMethod:@"POST"];
// Set header to accept JSON request
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// Your params
NSDictionary *params = @{@"data":@"value"};
// Change your 'params' dictionary to JSON string to set it into HTTP
// body. Dictionary type will be not understanding by request.
NSString *jsonString = [self getJSONStringWithDictionary:params];

// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

Hope this will help you. Happy coding! :)

like image 89
Thinh Phan Avatar answered Sep 28 '22 14:09

Thinh Phan


If someone looking for AFNetworking 3.0, here is code

NSError *writeError = nil;

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:120];

[request setHTTPMethod:@"POST"];
[request setValue: @"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue: @"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];

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

[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil 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);
        NSLog(@"Response: %@",response);
        NSLog(@"Response Object: %@",responseObject);

    }
}] resume];
like image 23
nadim Avatar answered Sep 28 '22 16:09

nadim