NSURLRequest POST导致空白提交

时间:2012-04-20 22:09:38

标签: iphone objective-c ios json

我正在尝试将数据发布到JSON Web服务。如果我这样做,我就能成功:

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产生了适当的输出。

1 个答案:

答案 0 :(得分: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];

这相当于您上面的卷曲调用。或者,如果你想使用curl发布JSON(正如你的ObjC代码示例所做的那样),你会这样做:

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