简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM