iOS,检查http或https服务器是否正在侦听特定端口

时间:2013-04-30 17:51:05

标签: ios

我需要查找一个Web服务器(有时是http,有时是https)正在侦听。我宁愿同步这样做并且有一个小的超时,例如2-3秒。

这样做的正确方法是什么?我需要向后兼容iOS 5。

更新:我需要在没有外部库的情况下完成。

1 个答案:

答案 0 :(得分:3)

由于OP无法使用外部库,请实施 NSURLConnectionDelegate 并使用:

- (void)testUrl:(NSString *)url
{
    // Create the request.
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                              cachePolicy:NSURLRequestReloadIgnoringCacheData
                                          timeoutInterval:3.0];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    int responseStatusCode = [httpResponse statusCode];

    NSLog(@"GOT STATUS CODE: %d", responseStatusCode);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Done!");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}