2012-04-20 78 views
0

我想将数据发布到JSON webservice。我可以成功,如果我这样做:NSURLRequest POST导致空白提交

curl -d "project[name]=hi&project[description]=yes" http://mypath.com/projects.json

我试图用这样的代码来完成它:

NSError *error = nil; 
NSDictionary *newProject = [NSDictionary dictionaryWithObjectsAndKeys:self.nameField.text, @"name", self.descField.text, @"description", nil]; 
NSLog(@"%@", self.descField.text); 
NSData *newData = [NSJSONSerialization dataWithJSONObject:newProject options:kNilOptions error:&error]; 
NSMutableURLRequest *url = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mypath.com/projects.json"]]; 
[url setHTTPBody:newData]; 
[url setHTTPMethod:@"POST"]; 
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:url delegate:self]; 

我请求创建一个新的条目,但该条目是空白名字和描述。我的NSLog在上面的代码产生适当的输出。

+0

:另外,如果你想使用curl张贴JSON(如您的ObjC代码示例在做),你会做它像这样表格数据? – Perception 2012-04-20 22:19:13

回答

2

你在这里混合了两件事。 webservice返回一个JSON结果http://mypath.com/projects.json,但在你的curl例子中,你的HTTP正文是一个普通的旧查询字符串表单体。以下是您需要做的工作:

NSError *error = nil; 
NSString * newProject = [NSString stringWithFormat:@"project[name]=%@&project[description]=%@", self.nameField.text, self.descField.text]; 
NSData *newData = [newProject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; // read docs on dataUsingEncoding to make sure you want to allow lossy conversion 
NSMutableURLRequest *url = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mypath.com/projects.json"]]; 
[url setHTTPBody:newData]; 
[url setHTTPMethod:@"POST"]; 
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:url delegate:self]; 

这将相当于您在上面所做的卷曲调用。为什么你在你的目标C例如发送JSON当你卷曲样品发送

curl -d '"{\"project\":{\"name\":\"hi\",\"project\":\"yes\"}}"' -H "Content-Type: application/json" http://mypath.com/projects.json

+0

谢谢。我刚开始玩这个网络的东西,并且对如何完成它感到困惑。在你的帮助下它像一个魅力一样工作! – 2012-04-21 02:14:17