3

可能重复:
Objective-C iPad 开发中的 POST

我对网络之类的东西非常缺乏经验,所以请善待。

我正在尝试使用以下表单数据发送发布请求

{"email":"JoeSmith@aol.com","password":"password","password_confirm":"password","name":"Joe Smith","cellphone":"4402415585","address":"Fake Street"}:

到目前为止,这是我所拥有的:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",SERVER_ADDRESS]] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                   timeoutInterval:10];
[request setHTTPMethod: @"POST"];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];

我的问题是我无法弄清楚如何在此请求中包含表单数据。我确信NSMutableURLRequest可以使用一种简单的方法,但我无法弄清楚是哪一种。

4

1 回答 1

8

您需要将 JSON 字符串转换为 NSData 格式。然后您就可以在 URLRequest 对象中将此数据设置为 HTTP 正文。

添加代码示例:

NSData* postData= [<yourJSON> dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  [request setHTTPMethod:@"POST"];
  [request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
  [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
  [request setHTTPBody:postData];

  NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request 
                                                                delegate:self];

  [connection start];

如果有更多帮助,请告诉我...

于 2013-01-12T20:16:36.310 回答