带有NSURLConnection的POST

编程入门 行业动态 更新时间:2024-10-21 09:26:45
本文介绍了带有NSURLConnection的POST-没有JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试用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&param2=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

本文发布于:2023-10-11 23:13:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NSURLConnection   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!