iphone - iOS:如何执行 HTTP POST 请求?

我正在着手进行 iOS 开发,我想让我的第一个应用程序之一执行 HTTP POST 请求。

据我所知,我应该通过 NSURLConnection 对象管理处理请求的连接,这迫使我拥有一个委托(delegate)对象,而委托(delegate)对象又将处理数据事件。

有人可以用一个实际的例子来澄清这个任务吗?

我应该联系一个 https 端点,发送身份验证数据(用户名和密码)并返回纯文本响应。

最佳答案

您可以按如下方式使用 NSURLConnection:

  1. 设置你的 NSURLRequest:使用 requestWithURL:(NSURL *)theURL 来初始化请求。

    如果您需要指定 POST 请求和/或 HTTP header ,请使用 NSMutableURLRequest

    • (void)setHTTPMethod:(NSString *)method
    • (void)setHTTPBody:(NSData *)data
    • (void)setValue:(NSString *)HTTPHeaderField 的值:(NSString *)field
  2. 使用 NSURLConnection 以 2 种方式发送您的请求:

    • 同步:(NSData *)sendSynchronousRequest:(NSURLRequest *)request returnedResponse:(NSURLResponse **)响应错误:(NSError **)error

      这将返回一个您可以处理的 NSData 变量。

      重要提示:请记住在单独的线程中启动同步请求以避免阻塞 UI。

    • 异步:(void)start

不要忘记设置你的 NSURLConnection 的委托(delegate)来处理连接,如下所示:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.data setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
    [self.data appendData:d];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"")
                                 message:[error localizedDescription]
                                delegate:nil
                       cancelButtonTitle:NSLocalizedString(@"OK", @"") 
                       otherButtonTitles:nil] autorelease] show];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];

    // Do anything you want with it 

    [responseText release];
}

// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    NSString *username = @"username";
    NSString *password = @"password";

    NSURLCredential *credential = [NSURLCredential credentialWithUser:username
                                                             password:password
                                                          persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

https://stackoverflow.com/questions/5537297/

相关文章:

objective-c - 错误 : writable atomic property cannot

ios - Objective-C中的方法重载?

ios - UITableView 设置为静态单元格。是否可以以编程方式隐藏某些单元格?

ios - iPhone/iPad的UILabel如何设置粗体和斜体?

ios - 在 iPhone App 中如何检测设备的屏幕分辨率

ios - 如何在 UIView 的顶部添加边框

ios - 更改 UITableView 部分标题的字体大小

ios - 如何比较 UIColors?

objective-c - 为什么在 iOS 中使用前导下划线重命名合成属性?

ios - SDK iOS 8.0 中的产品类型单元测试包需要代码签名