【发布时间】:2014-01-05 01:46:47
【问题描述】:
我正在异步执行 NSURL 请求。它在大多数情况下都可以正常工作,但有时它会为显然是伪造的主机返回200 OK。这是连接的代码:
-(void)checkConnectionForHost:(NSString*)host completion:(completion_t)completionHandler
{
NSURLRequest* request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:host]];
if([NSURLConnection canHandleRequest:request]){
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(completionHandler)
{
completionHandler(connectionError == nil && [(NSHTTPURLResponse*)response statusCode]==200);
}
}];
}
}
还有完成处理程序:
typedef void (^completion_t)(BOOL isReachable);
我在collectionView:cellForItem... 委托方法中为我的数据源中的每个单元格调用此命令。
我知道这不起作用的原因是因为我发送了一些随机主机,例如8107341897309,它立即返回0 状态,但随后更改为200。另外,如果我发送一个带有字符串的值,它会保持0。当我发送一个只有整数或小数的值时,它会一直跳来跳去。任何见解都会很棒!
编辑:所以有时当它连接时它返回一个0,而其他时候它返回一个200。我想说的是结果不一致。
编辑 2:决定记录我在 collectionView:cellForItemAtIndexPath 中得到的结果并得到了这个:
2014-01-04 19:22:53.390 ServerObserver[5624:4703] http://192.168.1.11 is Reachable? : 1. Index: 0
2014-01-04 19:22:53.414 ServerObserver[5624:3707] http://apple.com is Reachable? : 1. Index: 6
2014-01-04 19:22:53.619 ServerObserver[5624:4003] http://192.168.1.11 is Reachable? : 1. Index: 0
2014-01-04 19:22:53.697 ServerObserver[5624:5603] http://google.com is Reachable? : 1. Index: 1
2014-01-04 19:22:53.696 ServerObserver[5624:4003] http://pandora.com is Reachable? : 1. Index: 5
2014-01-04 19:22:53.705 ServerObserver[5624:4003] http://apple.com is Reachable? : 1. Index: 6
2014-01-04 19:22:53.732 ServerObserver[5624:5603] http://reddit.com is Reachable? : 1. Index: 4
2014-01-04 19:22:53.781 ServerObserver[5624:1803] http://google.com is Reachable? : 1. Index: 1
2014-01-04 19:22:53.893 ServerObserver[5624:5603] http://twitter.com is Reachable? : 1. Index: 3
2014-01-04 19:22:53.896 ServerObserver[5624:5603] http://reddit.com is Reachable? : 1. Index: 4
2014-01-04 19:22:53.891 ServerObserver[5624:1803] http://pandora.com is Reachable? : 1. Index: 5
2014-01-04 19:22:54.038 ServerObserver[5624:4003] http://twitter.com is Reachable? : 1. Index: 3
2014-01-04 19:22:54.268 ServerObserver[5624:5603] http://facebook.com is Reachable? : 1. Index: 2
2014-01-04 19:22:54.317 ServerObserver[5624:5603] http://facebook.com is Reachable? : 1. Index: 2
需要注意的是,垃圾 IP 甚至没有出现在这里,因为我检查了前面的方法,如果请求“可以发出”。但是,为什么每个 IP 被调用两次?每个单元只有一个 IP。
【问题讨论】:
-
介意解释一下:“马上返回了0状态,后来又变成了200”?
-
使用像 Charles Proxy 这样的网络分析器来准确查看发送和接收的内容。
-
对不起,我已经更新了 OP
-
当它返回零时,
response是什么(我打赌它是nil)和connectionError是什么(我打赌它报告连接错误)?当它是200时,data是什么(我敢打赌,如果您查看它,将其转换为字符串,它可能是您的 ISP 生成的 HTML 页面,上面写着“哦,我找不到那个网站,你的意思是 X 吗?”。)我的 ISP(Verizon FiOS)有这个令人难以置信的烦人功能(包括行为的不一致)。
标签: ios iphone objective-c nsurlconnection nsurlrequest