我正在尝试用Objective-C编写一个iPhone应用程序.我需要使用NSURLConnection来发布数据.我能找到的每个示例都涉及JSON;我不需要使用JSON.我需要做的就是发布数据并从PHP脚本获取简单的1或0(成功或失败).没什么.
I am trying to write an iPhone app in Objective-C. I need to POST data using NSURLConnection. Every example I can find deals with JSON; I do not need to use JSON. All I need to do is POST the data and get a simple 1 or 0 (succeed or fail) from a PHP script. Nothing more.
我遇到了这段代码,但是我不确定如何使用它或将其修改为不使用JSON:
I came across this code but I am not sure how to use it or modify it to not use JSON:
- (void)performRequest { NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"someplace/"]]; [request setValue:@"Some Value" forHTTPHeaderField:@"Some-Header"]; [request setHTTPBody:@"{\"add_json\":\"here\"}"]; [request setHTTPMethod:@"POST"]; [NSURLConnection connectionWithRequest:[request autorelease] delegate:self]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // Fail.. } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // Request performed. }推荐答案
这里是创建普通帖子的方法.
Here's how to create an ordinary post.
首先创建正确类型的请求:
First create a request of the right type:
NSURL *URL = [NSURL URLWithString:@"example/somepath"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; request.HTTPMethod = @"POST";现在将您的帖子数据格式化为URL编码的字符串,如下所示:
Now format your post data as a URL-encoded string, like this:
NSString *params = @"param1=value1¶m2=value2&etc...";请记住使用百分比编码对各个参数进行编码.您不能完全依靠NSString stringByAddingPercentEscapesUsingEncoding方法(谷歌找出原因),但这是一个好的开始.
Remember to encode the individual parameters using percent encoding. You can't entirely rely on the NSString stringByAddingPercentEscapesUsingEncoding method for this (google to find out why) but it's a good start.
现在,我们将帖子数据添加到您的请求中:
Now we add the post data to your request:
NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding]; [request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"]; [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request addValue:[NSString stringWithFormat:@"%i", [data length]] forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:data];仅此而已,现在只需使用NSURLConnection(或其他方式)正常发送您的请求即可.
And that's it, now just send your request as normal using NSURLConnection (or whatever).
要解释返回的响应,请参阅Maudicus的答案.
To interpret the response that comes back, see Maudicus's answer.
更多推荐
带有NSURLConnection的POST
发布评论