如何在iOS中发布请求中发送表单数据?

Joe*_*lin 3 iphone url post objective-c ios

可能重复:
在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];
Run Code Online (Sandbox Code Playgroud)

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

iCr*_*ive 8

您需要将JSON字符串转换为NSData格式.然后,您就可以将此数据设置为URLRequest对象中的HTTP Body.

添加代码示例:

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];
Run Code Online (Sandbox Code Playgroud)

如有任何帮助,请告诉我......