检查URL中特定页面的可访问性

在我阅读了这个问题的答案后,我发现使用reachabilityWithHostName不能使用这样的URL: mySite.com/service.asmx ,无论如何都要使用reachabilityWithHostName或任何reachability类方法检查此URL的reachabilityWithHostName reachability

非常感谢提前。

Reachability类和-reachabilityWithHostname:旨在成为一种快速,快速的快速机制,用于确定您是否具有与主机的基本网络连接。 如果您需要validation是否可以下载特定的URL,则需要使用NSURLConnection来检索URL的内容,以validation它是否真正可用。

根据您是否需要在前台或后台执行此操作,您可以使用简单但阻塞:

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

或者您可以使用更复杂的方法创建NSURLConnection对象,设置委托以接收响应并等待这些响应进入。

对于简单的情况:

  NSURL *myURL = [NSURL URLWithString: @"http://example.com/service.asmx"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: myURL]; [request setHTTPMethod: @"HEAD"]; NSURLResponse *response; NSError *error; NSData *myData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error]; 

如果你收到一个非零的myData,你就有了某种连接。 responseerror将告诉您服务器对您的响应(在响应的情况下,如果您收到非零的myData)或发生了什么样的错误,在nil myData的情况下。

对于非平凡的案例,您可以从Apple的使用NSURLConnection获得良好的指导。

如果您不想停止前台进程,可以通过两种不同的方式执行此操作。 上面的文档将提供有关如何实现委托等的信息。但是,更简单的实现是使用GCD在后台线程上发送同步请求,然后在完成后在主线程上发送消息。

像这样的东西:

  NSURL *myURL = [NSURL URLWithString: @"http://example.com/service.asmx"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: myURL]; [request setHTTPMethod: @"HEAD"]; dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_BACKGROUND, NULL), ^{ NSURLResponse *response; NSError *error; NSData *myData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error]; BOOL reachable; if (myData) { // we are probably reachable, check the response reachable=YES; } else { // we are probably not reachable, check the error: reachable=NO; } // now call ourselves back on the main thread dispatch_async( dispatch_get_main_queue(), ^{ [self setReachability: reachable]; }); }); 

如果要检查URL的可访问性 (通常使用的是对主机名),只需使用NSURLConnection执行HEAD请求。