2011-10-30 91 views
16

我想找到一種方法,使用AFNetworking,將Content-Type頭設置爲application/json,並在主體中使用JSON進行POST。我在文檔中看到的方法(postPath和requestWithMethod)都採用參數字典,我假設這些參數是以標準格式語法編碼的。有誰知道一種方法來指導AFHTTPClient爲身體使用JSON,還是我需要自己寫請求?使用AFHTTPClient發佈JSON作爲POST請求的主體

回答

23

我繼續從他們的master branch檢查出最新的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編碼是默認根據line 170line 268

+11

咦,我沒有意識到JSON設定爲默認編碼。這是一個錯誤(URL表單編碼一直是我的默認打算;我不知道這是如何滑入)。 @EricAndres:請注意這一點,並手動將參數編碼設置爲JSON,在您的代碼中使用'self.parameterEncoding = AFJSONParameterEncoding;'。 – mattt

+0

太棒了,謝謝你的回覆。稍後當我有機會時,我會嘗試設置self.parameterEncoding。 –

+0

hmm ... json不是默認編碼,但NVP是(截至2013年初) – stackOverFlew

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

關鍵部分:

[client setParameterEncoding:AFJSONParameterEncoding]; 
+1

非常感謝! 你說得對,'[客戶端setParameterEncoding:AFJSONParameterEncoding];'丟失。 但此外似乎這也是實際使用NSDictionary所需的:'[client registerHTTPOperationClass:[AFJSONRequestOperation class]];' – thedp

+0

非常感謝。你拯救我的一天! – kb920