使用AFHTTPClient作为POST请求的主体发布JSON

我试图find一种方法,使用AFNetworking,将Content-Type头设置为应用程序/ json,并在主体中使用JSON进行POST。 我在文档中看到的方法(postPath和requestWithMethod)都带有一个参数字典,我假设它是以标准格式语法编码的。 有谁知道一种方法来指导AFHTTPClient使用JSON的身体,还是我需要自己写请求?

我继续从他们的主分支中检查出最新的AFNetworking。 开箱即用,我能够得到所需的行为。 我看了看,似乎是最近的变化(10月6日),所以你可能只需要拉最新的。

我写了下面的代码来提出请求:

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

在我的代理下,我可以看到原始请求:

 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"} 

从AFHTTPClient源你可以看到JSON编码是基于行170和行268的默认值。

对我来说,json不是默认的编码。 您可以手动将其设置为这样的默认编码:

(使用Evan的代码)

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

关键部分:

 [client setParameterEncoding:AFJSONParameterEncoding]; 
    Interesting Posts