iOS

Simple GET/POST AFNetworking

UPDATE: For AFNetworking 2.0, refer to this tutorial instead.

AFNetworking is the choice for iOS/Mac developers when it comes to choosing a HTTP library.

ASIHTTPRequest used to be the choice, until 2011 when it became inactive.

I am one of the many who is forced to switch camp.

In many ways, it seems AFNetworking would be better. It uses blocks!

However, I find the documentation lacking. It has an overview, getting started, introduction, complete reference, … But yet, it didn’t provide example on how you make a simple HTTP GET or POST.

Here is how you do it:

GET

1
2
3
4
5
6
7
8
9
10
11
12
13
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://samwize.com/"]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
                                                        path:@"http://samwize.com/api/pigs/"
                                                  parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Print the response body in text
    NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
[operation start];

POST

POST a urlencoded form name=piggy in the http body.

1
2
3
4
5
6
7
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://samwize.com/"]];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                        path:@"http://samwize.com/api/pig/"
                                                  parameters:@{@"name":@"piggy"}];

// Similar to GET code ...

If you want to POST a json such as {"name":"piggy"}, you change the encoding:

1
[httpClient setParameterEncoding:AFJSONParameterEncoding];

If you want to do a multi-part POST of an image, you do this:

1
2
3
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"http://samwize.com/api/pig/photo" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

This simple guide has been helped by this, this and this.

Pitfalls

Do not use [[AFHTTPClient alloc] init], as that does not initialize a lot of stuff. Use initWithBaseURL instead.

For instance, if in the above example (POST JSON) you had used init, the Content-Type will be

application/json; charset=(null)

Charset should be utf-8, not null.

Comments