[英]NSURLRequest POST resulting in blank submission
我正在尝试将数据发布到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产生了适当的输出。
你在这里混淆了两件事。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.