AFHTTPSessionManager add body to POST
Asked Answered
C

2

11

I need too make a post request to my server.

With AFHTTPRequestOperation is very simple just use:

[request setHTTPBody: [requestBody dataUsingEncoding:NSUTF8StringEncoding]];

However i can't find any example how use the same approach using the AFHTTPSessionManager.

Using the method:

[self POST:@"extraLink" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

} success:^(NSURLSessionDataTask *task, id responseObject) {

} failure:^(NSURLSessionDataTask *task, NSError *error) {

}];

How i add the the body to the "AFMultipartFormData"?

Thanks in advace

Cockaigne answered 10/10, 2014 at 11:41 Comment(1)
example: #20686679Buffer
D
15

As taken from the AFNetworking home page, to create a multipart/form-data request, you call appendPartWithFileURL:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

But AFHTTPRequestOperationManager is deprecated. So, instead, use AFHTTPSessionManager, for which the syntax of POST with the constructingBodyWithBlock is very similar:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} progress:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Alternatively, if you want to post a request of the form foo=bar&key=value&... (i.e. an application/x-www-form-urlencoded request), you would do something like:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *parameters = @{@"foo": @"bar", @"key": @"value"};
[manager POST:@"http://example.com/resources.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error: %@", error);
}];
Demerol answered 10/10, 2014 at 11:47 Comment(7)
There is another option to attach the data to the body? I have a string with a list "key=value&key=value&..." which is my body request. Do you know any way to add a plain string? @DemerolCockaigne
That key=value&key=value&... format is an application/x-www-form-urlencoded content type request (whereas the above creates a multipart/form-data request). If you need the application/x-www-form-urlencoded format, use the other rendition of POST without the constructingBodyWithBlock parameter.Demerol
sorry @Demerol but I did not understand you fully. Can you give me an example of how to add the body using the other POST method? ThanksCockaigne
just to confirm @Rob, i still need to convert my object "NSString" to a NSDictionary struture? ThanksCockaigne
Yes, you probably want to that (because AFNetworking will do the necessary percent-escaping that one needs to do for application/x-www-form-urlencoded requests). I guess you could create the percent-escaped body of the request yourself and then build the request yourself, but that's a lot more work.Demerol
i get a warning 'Post:parameters:success:failure' is depreciated when i use the alternative exampleBailable
@Edwin - Yep, it now has rendition with progress block. See revised answer.Demerol
H
5

Try this other way.

I'm converting my image in data format which is imageData.

NSData *imageData=nil;
imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"yourimageName"],0.2);
NSMutableDictionary *dict=[NSMutableDictionary new];
[dict setObject:@"user1" forKey:@"param_name1"];
[dict setObject:@"User2" forKey:@"param_name2"];

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
manager.responseSerializer = [AFJSONResponseSerializer
                              serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager POST:@"API NAME" parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

 if(imageData)
 {
     [formData appendPartWithFileData:imageData  name:@"param_name" fileName:@"filename.jpg" mimeType:@"image/jpeg"];
 }
 } progress:^(NSProgress * _Nonnull uploadProgress)
 {
     NSLog(@"%@",uploadProgress);
 } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     NSLog(@"%@",responseObject);

 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
     NSLog(@"%@",error);

 }];
Honeysucker answered 5/9, 2016 at 7:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.