ios - 发送帖子请求 IOS 7

标签 ios http post

好吧,我一直在尝试适应 Objective C,这对我来说就像坐过山车一样,无论如何,我只是想向服务器发送一个简单的 post 请求,但是它看起来并不像以前那么简单安卓。目前我有以下方法:

-(void)postMethod
{

    [self.connection cancel];

    //initialize new mutable data
    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;

    //initialize url that is going to be fetched.
    NSURL *url = [NSURL URLWithString:@"http://blank.com/register.php"];

    //initialize a request from url
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];

    //set http method
    [request setHTTPMethod:@"POST"];
    //initialize a post data
    NSString *postData = @"username=postTest&displayname=testingPoster&password=postest&passwordc=postest&email=posttesting%40posttest.com&bio=I+am+tesring+the+post+test&skills=I+am+a+hacka&interests=hacing+and+cracking&skills_needed=some+php+skills&company=Post+testing+the+script&dob=naaaaaa&occupation=Qoekkk";
    //Here you can give your parameters value

    //set request content type we MUST set this value.

    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    //set post data of request
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];

    //initialize a connection from request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.connection = connection;


    //start the connection
    [connection start];
}

我有一个按钮来调用该函数:

- (IBAction)register:(id)sender {

    [self postMethod];


}

我确实确保在头文件中包含了 NSURLConnectionDataDelegate,但是当我单击按钮时尝试发送请求时,它不会通过,只会停止程序,不会出现任何错误。任何建议,我一直在网上搜索只是为了学习如何发送帖子请求,我认为这应该不是很困难。

为了以防万一,我正在使用适用于 ios 7 的最新 iphone sdk。

最佳答案

请注意,对于 iOS 7 NSURLSession是推荐的方式。 NSURLConnection 在未来的版本中可能会被弃用。您可以使用 URL session tasks 三种类型之一发出 POST 请求。 。 NSURLSessionDataTask几乎等同于 NSURLConnection。 NSURLSessionUploadTaskNSURLSessionDownloadTask (将接收到的数据写入磁盘)可以在后台 session 中使用,并且即使您的应用程序挂起或崩溃也可以继续(在另一个进程中)。更多内容可阅读this guide .

关于ios - 发送帖子请求 IOS 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213994/

相关文章:

iphone - 当 NSString 包含表情符号时如何获取 NSString 大小?

ios - 通过 Fabric 安装 Twitter,登录有效,请求 Tweets 的持续错误

ios - xcode 命令行构建因 com.apple.compilers.llvm.clang.1_0.compiler 失败

django - nginx、django 和 x_requested_with : request. is_ajax() 返回 False

c++ - QprogressBar 在一秒内从 0 跳到 100,如何使其平滑

c# - 在读取页面源代码时,如何知道将使用 POST 发送哪些参数?

http - HTTP 中的 POST 和 PUT 有什么区别?

ios - Bootstrap 图标无法在 IOS 设备中正确显示

http - 仅从远程原始文件嵌入 jpg?

.net - 阅读 GetResponseStream() 的最佳方式是什么?