iPhone:httppost请求
我需要从我的iphone应用程序向服务器发送一些详细信息。我有详细信息,如iPhone:httppost请求,iphone,objective-c,ios,http-post,nsurlrequest,Iphone,Objective C,Ios,Http Post,Nsurlrequest,我需要从我的iphone应用程序向服务器发送一些详细信息。我有详细信息,如ID、姓名、数量的独立数组和带有姓名、地址、电话和电子邮件的字符串我需要将NSmutable数组数据更改为此JSON格式 [ {"id":"139","name":"Samosa","quantity":"332","spice":"hot"}, {"id":"149","name":"rice","quantity":"4","spice":"mild"},
ID、姓名、数量的独立数组
和带有姓名、地址、电话和电子邮件的字符串
我需要将NSmutable数组数据更改为此JSON格式
[
{"id":"139","name":"Samosa","quantity":"332","spice":"hot"},
{"id":"149","name":"rice","quantity":"4","spice":"mild"},
.....
]
我的一个疑问是[request setHTTPMethod:@“POST”]代码>
以上行是否足以设置POST请求
如何将上述详细信息添加到POST请求中?还不够。您还需要(至少):
使用JSON序列化程序。你可以用。对于SBJSON,代码如下所示:
SBJsonWriter *jsonWriter = [[[SBJsonWriter alloc] init] autorelease];
NSString *jsonParams = [jsonWriter stringWithObject:<your-NSArray>];
用于将post数据添加到HTTP请求对象。
用于序列化数组
NSMutableArray *array = getSomeArray();
NSError *err;
NSData *json;
json = [NSJSONSerialization dataWithJSONObject:array options:0 error:&err];
if (err) {
// handle error
}
NSURL *url = getSomeURL();
NSMutableURLRequest *req;
req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:json];
// send your request
NSString *postData = [jsonParams stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:postURL];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableArray *array = getSomeArray();
NSError *err;
NSData *json;
json = [NSJSONSerialization dataWithJSONObject:array options:0 error:&err];
if (err) {
// handle error
}
NSURL *url = getSomeURL();
NSMutableURLRequest *req;
req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:json];
// send your request