我对网络等很缺乏经验,所以请善待。
我正在尝试发送包含以下表单数据的帖子请求
{"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
的简单方法,但我无法找出哪一种方法。
答案 0 :(得分: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];
如果有任何帮助,请告诉我......