iphone - 如何在 iOS 的 post 请求中发送表单数据?

标签 iphone ios objective-c url post

<分区>

Possible Duplicate:
POST in Objective-C iPad dev

我在网络等方面非常缺乏经验,所以请客气。

我正在尝试发送带有以下表单数据的发布请求

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

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

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 方法可以使用,但我还没弄清楚是哪一个。

最佳答案

您需要将 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];

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

关于iphone - 如何在 iOS 的 post 请求中发送表单数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14297310/

相关文章:

iphone - 在 TabBar 中更改选项卡时,UIButtons 文本显得更暗

ios - 在 Xcode 4.2 上,应用程序总是在调试器中暂停

iphone - 针对越狱 iPhone 的 Kill 命令

ios - 将数据从 UICollectionView 快速/传递到 DetailView/自定义按钮

ios - 如何区分单击并按下UIButton iOS

ios - 测量蜂窝信号强度

iphone - 如何设置初始界面方向?

android - 数据库密码保护移动应用 iPhone/Android

iphone - IOS应用程序的文档有文件大小限制吗

iphone - UIScrollView View