Posting JSON as the body of a POST request using AFHTTPClient

12,798

Solution 1

I went ahead and checked out the latest AFNetworking from their master branch. Out of the box I was able to get the desired behavior. I looked and it seems like a recent change (October 6th) so you might just need to pull the latest.

I wrote the following code to make a request:

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:8080/"]];
[client postPath:@"hello123" parameters:[NSDictionary dictionaryWithObjectsAndKeys:@"v1", @"k1", @"v2", @"k2", nil] 
         success:^(id object) {
             NSLog(@"%@", object);
         } failure:^(NSHTTPURLResponse *response, NSError *error) {
             NSLog(@"%@", error);
         }];
[client release];

Under my proxy I can see the raw request:

POST /hello123 HTTP/1.1
Host: localhost:8080
Accept-Language: en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us;q=0.8
User-Agent: info.evanlong.apps.TestSample/1.0 (unknown, iPhone OS 4.3.2, iPhone Simulator, Scale/1.000000)
Accept-Encoding: gzip
Content-Type: application/json; charset=utf-8
Accept: */*
Content-Length: 21
Connection: keep-alive

{"k2":"v2","k1":"v1"}

From the AFHTTPClient source you can see that JSON encoding is the default based on line 170, and line 268.

Solution 2

For me, json was NOT the default encoding. You can manually set it as the default encoding like this:

(using Evan's code)

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:8080/"]];

[client setParameterEncoding:AFJSONParameterEncoding];

[client postPath:@"hello123" parameters:[NSDictionary dictionaryWithObjectsAndKeys:@"v1", @"k1", @"v2", @"k2", nil]
         success:^(id object) {
             NSLog(@"%@", object);
         } failure:^(NSHTTPURLResponse *response, NSError *error) {
             NSLog(@"%@", error);
         }];
[client release];

the crucial part:

[client setParameterEncoding:AFJSONParameterEncoding];
Share:
12,798
Eric Andres
Author by

Eric Andres

Updated on June 18, 2022

Comments

  • Eric Andres
    Eric Andres about 2 years

    I am trying to find a way, using AFNetworking, to set the Content-Type header to be application/json and to POST with JSON in the body. The methods that I'm seeing in the documentation (postPath and requestWithMethod) both take a dictionary of parameters, which I assume is encoded in the standard form syntax. Does anyone know of a way to instruct AFHTTPClient to use JSON for the body, or do I need to write the request on my own?