2014-03-19 15 views
0

我試圖使用AFHTTPRequestOperation(通過AFHTTPRequestOperationManager)將一些信息(例如,「foo = bar」)傳輸到需要JSON的後端,使用像這樣的設置:如何使用AFHTTPRequestOperation在表單域中包含JSON

- (void) postTest { 
NSString *completePath = @"https://httpbin.org/post"; 
NSDictionary *dataToJSONfy = @{@"foo":@"bar"}; 
NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dataToJSONfy options:kNilOptions error:&error]; 

NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:completePath parameters:nil]; 
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:jsonData]; 

AFHTTPRequestOperation *operation = 
[self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id JSON) { 
    NSLog(@"... success! %@", JSON); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"... failure! Error: %@", error); 
}]; 

[self.operationQueue addOperation:operation]; 
} 

這都說明了這樣

{ 
args =  { 
}; 
data = "{\"foo\":\"bar\"}"; 
files =  { 
}; 
form =  { 
}; 
headers =  { 
    [...] 
}; 
json =  { 
    foo = bar; 
}; 
origin = [...]; 
url = "http://httpbin.org/post"; 
} 

問:什麼,我需要以改變,包括我的信息(「富=欄;」)中的「形式=」而不是'json ='bi T'

+0

沒有得到你的迴應。所以你不想包括json,但formdata? –

+0

我想在帖子中包含有效的JSON(例如之前存儲的某些服務器響應),但根據API規範,一切都應該位於'form = {};'部分。所以我想我想要JSON作爲formdata。 – Gamma

+0

給你寫了一個答案..只是不把json放在body中,但是使用字符串作爲中間值 –

回答

1

我想包括有效的JSON聲明NSDictionary中塊(例如存儲一些服務器響應之前),但根據API規範,一切都應該位於'form = {};''之下部分。所以我想我想要JSON作爲formdata。

NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dataToJSONfy options:kNilOptions error:&error]; 

//new! 
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
NSString *bodyString = [NSString stringWithFormat:@"{'Form': '%@'}, jsonString]; //! not 100% what you want. I stick with valid JSON here 
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; 

NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:completePath parameters:nil]; 
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

[request setHTTPBody:bodyData]; //! 
+0

我沒有得到這個問題,但是由於body不是JSON(_bodyData_),所以不能工作,但Content-Type假裝它是。它也不是已知的MIME類型。 – CouchDeveloper

+0

這是他想要的。所有;)我得到它不是有效的json –

+0

也許contentType確實是錯誤的 –

-1

首先你只需要後測方法類似

__block NSDictionary *dict=[NSDictionary alloc] init]; 

後和成功塊,你應該使用

dict=[NSJSONSerlization JSONObjectWithData:JSON options:NSJSONReadingAllowFragments error:nil]; 
NSLog(@"... success! %@", dict); 
+0

他想POST數據 –

相關問題