I am trying to POST data to a JSON webservice. I can succeed if I do this:
curl -d "project[name]=hi&project[description]=yes" http://mypath.com/projects.json
I’m trying to use code like this to accomplish it:
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];
My request creates a new entry, but that entry is blank in both the name and description. My NSLog in the above code produces the appropriate output.
You are mixing up two things here. The webservice returns a JSON result
http://mypath.com/projects.jsonbut in your curl example, your HTTP body is a plain old querystring form body. Here’s what you need to do to make this work:This will be equivalent to the curl call you made above. Alternatively, if you wanted to post JSON (as your ObjC code example was doing) using curl, you would do it like so:
curl -d '"{\"project\":{\"name\":\"hi\",\"project\":\"yes\"}}"' -H "Content-Type: application/json" http://mypath.com/projects.json