gpt4 book ai didi

objective-c - 正确处理 NSURLConnection 错误

转载 作者:行者123 更新时间:2023-12-03 17:44:52 25 4
gpt4 key购买 nike

我设置了一个简单的表单界面,将用户名和密码信息发送到服务器:(工作)

    NSString *postData = [NSString stringWithFormat:@"user=%@&pass=%@",[self urlEncodeValue:sysUsername],[self urlEncodeValue:password]];
NSLog(@"Post data -> %@", postData);
///
NSData* postVariables = [postData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString* postLength = [NSString stringWithFormat:@"%d", [postVariables length]];
NSURL* postUrl = [NSURL URLWithString:@"http://localhost/~csmith/cocoa/test.php"];
[request setURL:postUrl];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: postVariables];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSLog(@"Post data SENT & returned -> %@", returnData);

如何处理连接错误,例如没有互联网连接、防火墙等。另外,此方法是否使用系统范围的代理设置?我的许多用户都使用代理。

非常感谢!

最佳答案

首先,您不应使用同步请求,而应使用异步请求,并使用 indeterminate progress indicators 指示事件.

使用异步请求时,必须设置委托(delegate)实现delegate methods ,特别是:

来自文档:

Unless a NSURLConnection receives a cancel message, the delegate will receive one and only one of connectionDidFinishLoading:, or connection:didFailWithError: message, but never both. In addition, once either of messages are sent, the delegate will receive no further messages for the given NSURLConnection.

至于最后一个问题:

Also, does this method use the system-wide proxy settings?

是的,NSURLConnection会自动使用它们。

关于objective-c - 正确处理 NSURLConnection 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2989557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com