Cocoa如何做POST请求?

时间:2012-07-04 15:14:41

标签: ios cocoa request http-post

我已经按照一些教程,但我坚持做Post发送请求。我只想发送3个参数,一个URL和响应的hadle。它必须是异步的,因为它会给我一些图像,我想在视图上一个接一个。

你能帮帮我们吗?

2 个答案:

答案 0 :(得分:2)

这涵盖得很好here

但我这样做的方式让我觉得更简单,我会告诉你的。在SO和其他提供这方面知识的地方仍有很多问题。

首先,我们使用参数设置请求:

- (NSData *)executePostCall {
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", YOUR_URL]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSString *requestFields = [NSString stringWithString:@""];
    requestFields = [requestFields stringByAppendingFormat:@"parameter1=%@&", parameter1];
    requestFields = [requestFields stringByAppendingFormat:@"parameter2=%@&", parameter2];
    requestFields = [requestFields stringByAppendingFormat:@"parameter3=%@", parameter3];

    requestFields = [requestFields stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSData *requestData = [requestFields dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestData;
    request.HTTPMethod = @"POST";

    NSHTTPURLResponse *response = nil;
    NSError *error = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    if (error == nil && response.statusCode == 200) {
      NSLog(@"%i", response.statusCode);
    } else {
      //Error handling
    }

    return responseData;
}

这必须包含在一个块中,因为我们无法在主线程上执行它,因为它会锁定我们的应用程序,这是不受欢迎的,所以我们执行以下操作来包装此请求,我会将剩下的细节留给您:

dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);

dispatch_async(downloadQueue, ^{
  NSData *result = [self executePostCall];
  dispatch_async(dispatch_get_main_queue(), ^{
    // Handle your resulting data
  });
});
dispatch_release(downloadQueue);

答案 1 :(得分:0)

使用NSURLRequest。您可以在后台下载文件,并在收到代理通知后显示它们:Downloading to a Predetermined Destination