我正在着手进行 iOS 开发,我想让我的第一个应用程序之一执行 HTTP POST 请求。
据我所知,我应该通过 NSURLConnection
对象管理处理请求的连接,这迫使我拥有一个委托(delegate)对象,而委托(delegate)对象又将处理数据事件。
有人可以用一个实际的例子来澄清这个任务吗?
我应该联系一个 https 端点,发送身份验证数据(用户名和密码)并返回纯文本响应。
最佳答案
您可以按如下方式使用 NSURLConnection:
设置你的 NSURLRequest
:使用 requestWithURL:(NSURL *)theURL
来初始化请求。
如果您需要指定 POST 请求和/或 HTTP header ,请使用 NSMutableURLRequest
和
(void)setHTTPMethod:(NSString *)method
(void)setHTTPBody:(NSData *)data
(void)setValue:(NSString *)HTTPHeaderField 的值:(NSString *)field
使用 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/