iOS:如何执行 HTTP POST 请求? [英] iOS: how to perform a HTTP POST request?

查看:32
本文介绍了iOS:如何执行 HTTP POST 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在接触 iOS 开发,我想要我的第一个应用程序来执行 HTTP POST 请求.

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

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

我应该联系 https 端点发送身份验证数据(用户名和密码)并获取纯文本响应.

解决方案

您可以使用 NSURLConnection 如下:

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

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

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

    • 同步:(NSData *)sendSynchronousRequest:(NSURLRequest *)requestreturningResponse:(NSURLResponse **)response error:(NSError **)error

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

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

    • 异步:(void)start

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

- (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", @"")消息:[错误本地化描述]代表:无cancelButtonTitle:NSLocalizedString(@"OK", @"")otherButtonTitles:nil] 自动释放] 显示];}- (void)connectionDidFinishLoading:(NSURLConnection *)connection {NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];//用它做任何你想做的事[响应文本发布];}//如果需要,处理基本身份验证质询- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {NSString *用户名 = @"用户名";NSString *password = @"password";NSURLCredential *credential = [NSURLCredential credentialWithUser:username密码:密码持久性:NSURLCredentialPersistenceForSession];[[挑战发送者] useCredential:credential forAuthenticationChallenge:challenge];}

I'm approaching iOS development and I'd like to have one of my first applications to perform a HTTP POST request.

As far as I can understand, I should manage the connection which handles the request via a NSURLConnection object, which forces me to have a delegate object, which in turn will handle data events.

Could someone please clarify the task with a practical example?

I should contact an https endpoint sending authentication data (username and password) and getting back a plain text response.

解决方案

You can use NSURLConnection as follows:

  1. Set your NSURLRequest: Use requestWithURL:(NSURL *)theURL to initialise the request.

    If you need to specify a POST request and/or HTTP headers, use NSMutableURLRequest with

    • (void)setHTTPMethod:(NSString *)method
    • (void)setHTTPBody:(NSData *)data
    • (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
  2. Send your request in 2 ways using NSURLConnection:

    • Synchronously: (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error

      This returns a NSData variable that you can process.

      IMPORTANT: Remember to kick off the synchronous request in a separate thread to avoid blocking the UI.

    • Asynchronously: (void)start

Don't forget to set your NSURLConnection's delegate to handle the connection as follows:

- (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];
}

这篇关于iOS:如何执行 HTTP POST 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆