16

我正在尝试找到一种方法,使用 AFNetworking 将 Content-Type 标头设置为 application/json 并在正文中使用 JSON 进行 POST。我在文档中看到的方法(postPath 和 requestWithMethod)都采用一个参数字典,我假设它是以标准形式语法编码的。有谁知道指示 AFHTTPClient 使用 JSON 作为正文的方法,还是我需要自己编写请求?

4

2 回答 2

23

我继续从他们的master 分支检查了最新的 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行的默认编码。

于 2011-10-30T09:43:26.357 回答
13

对我来说,json 不是默认编码。您可以手动将其设置为默认编码,如下所示:

(使用埃文的代码)

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];
于 2013-03-17T06:59:29.370 回答