【问题标题】:Why i get timeout erros when page is not available为什么页面不可用时出现超时错误
【发布时间】:2012-12-19 06:46:19
【问题描述】:

我使用NSString 方法initWithContentsOfURL:usedEncoding:error: 来获取某些页面的内容。我注意到,当我尝试访问的页面不存在时,此方法会执行很长时间,然后因超时错误而失败。我尝试将 NSURLRequestNSURLConnection 类用于相同的目的,但得到相同的结果 - 执行时间长然后超时错误。 当我尝试在浏览器中打开同一页面时,我会更快地得到响应并返回页面不可用错误。

看起来可可方法不对页面名称进行 dns 解析,或者它们对该操作的超时时间更长。

所以我的问题是,我使用的可可方法可以解析 dns 吗?如果他们不这样做怎么办?

我使用的代码示例:

NSURL* url = [NSURL URLWithString:@"http://unexisting.domain.local"]; 
NSError* err = nil;
NSString* content = [NSString stringWithContentsOfURL:url usedEncoding:nil error:&err];

if (err) {
    NSLog(@"error: %@", err); 
} else {
    NSLog(@"content: %@", content);
}

NSURL* url = [NSURL URLWithString:@"http://unexisting.domain.local"]; 
NSURLRequest* request = [NSURLRequest requestWithURL:url];

NSURLResponse* response = nil;
NSError* err = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

if (err) {
    NSLog(@"error: %@", err); 
} else {
    NSString* content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"content: %@", content);
}

谢谢!

【问题讨论】:

  • 为什么使用“.local”作为顶级域名?出于测试目的还是仅在本地网络中?
  • 如果我将您的代码与 url unexisting.domain.ch 一起使用,它会非常快。
  • 我使用本地只是为了测试目的。实际上,我也必须访问本地网络中的主机。当使用“unexisting.com”时你是对的——它很快,而不是当用户只是“不存在”时——它会挂断一段时间。我的本地网络中的 dns 可能存在一些问题...

标签: objective-c cocoa http


【解决方案1】:

Gene M. answered 如何使用 SCNetworkReachability 来做到这一点。这是示例代码:

bool success = false;
const char *host_name = [@"stackoverflow.com" 
                         cStringUsingEncoding:NSASCIIStringEncoding];

SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,
                                                                        host_name);
SCNetworkReachabilityFlags flags;
success = SCNetworkReachabilityGetFlags(reachability, &flags);
bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && 
                             !(flags & kSCNetworkFlagsConnectionRequired);
if (isAvailable) {
    NSLog(@"Host is reachable: %d", flags);
}else{
    NSLog(@"Host is unreachable");
}

【讨论】:

    【解决方案2】:

    监控可达性(设备连接性)并按照上面的说明对其做出反应,这绝对是一种很好的做法。

    还可以实现NSURLConnectionDelegate协议及其方法,如

     - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
          NSLog(@"**ERROR** %@", error);
          // Respond to error
     }
    

    如果你没有连接,你应该得到一个 NSURLConnection 错误代码 999 和 NSURLErrorCancelled = -999 和/或 NSURLErrorNotConnectedToInternet = -1009 如果你没有连接,等等。至少你会有一个关于发生了什么的报告开。

    文档: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html

    【讨论】:

      猜你喜欢
      • 2022-11-25
      • 2022-06-15
      • 2020-05-01
      • 2021-10-10
      • 2020-10-27
      • 1970-01-01
      • 2021-03-07
      • 2022-11-05
      • 1970-01-01
      相关资源
      最近更新 更多