使用AFHTTPClient将JSON发布为POST请求的正文

Eri*_*res 16 objective-c ios afnetworking

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

Eva*_*van 23

我继续从他们的主分公司检查出最新的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];
Run Code Online (Sandbox Code Playgroud)

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

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"}
Run Code Online (Sandbox Code Playgroud)

从AFHTTPClient源可以看出,JSON编码是基于第170 第268 的默认编码.

  • 嗯,我没有意识到JSON被设置为默认编码.这是一个错误(URL表单编码一直是我打算默认的;我不确定它是如何滑入的).@EricAndres:请注意,这和参数编码手动设置为JSON,用`self.parameterEncoding = AFJSONParameterEncoding;`在你的代码. (11认同)

sta*_*lew 13

对我来说,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];
Run Code Online (Sandbox Code Playgroud)

关键部分:

[client setParameterEncoding:AFJSONParameterEncoding];
Run Code Online (Sandbox Code Playgroud)