POST-запрос с JSON телом AFNetworking 2.0

Есть ли способ отправить запрос POST с телом JSON, используя AFNetworking ~> 2.0?

Я пытался с помощью:
manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager POST:<url> parameters: @{@"data":@"value"} success: <block> failure: <block>'

но это не работает Любая помощь с благодарностью. Спасибо

2 ответа

Если кто-то ищет AFNetworking 3.0, вот код

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

Вы можете добавить свое тело JSON в NSMutableURLRequest не прямо в parameters:, Смотрите мой пример кода:

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

Надеюсь, что это поможет вам. Удачного кодирования!:)

Другие вопросы по тегам