2012-04-20 2 views
0

JSON WebサービスにデータをPOSTしようとしています。私の要求は、新しいエントリを作成しますが、そのエントリは空白であるNSURLRequest POSTの結果が空白になりました

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]; 

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

私はそれを達成するために、このようなコードを使用しようとしている:私はこれを行う場合には、成功することができます名前と説明の両方。上記のコードのNSLogは、適切な出力を生成します。

+0

をあなたのカールサンプルを送信するときに、あなたのObjective Cの例ではJSONを送信している理由フォームデータ? – Perception

答えて

2

ここでは2つのものを混在させています。 webserviceはJSON結果http://mypath.com/projects.jsonを返しますが、あなたのカールの例では、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呼び出しと同じです。あなたは(あなたにObjCのコード例がやったように)カールを使用してJSONを投稿したい場合あるいは、あなたはそうのようにそれを行うだろう:

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

+0

ありがとうございます。私はちょうどこのネットワークのもので遊んで始めて、それをどうやってやるべきかについて混乱しました。あなたの助けを借りて魅力的に働いた! –

関連する問題