1

我需要在不使用缓存的情况下检查我的服务器上是否存在文件。我使用的方法都是返回200,即使文件不存在,所以我只能假设是缓存问题,或者我的代码有问题。

这是我的代码:出于参数考虑..此示例中的 URL 已更改,但我的代码中的 url 是正确的。

NSString *auth = [NSString stringWithFormat:@"http://www.mywebsite.com/%@.txt",[self aString]];
NSURL *authURL = [NSURL URLWithString:auth];

NSURLRequest* request = [NSURLRequest requestWithURL:authURL 
                                         cachePolicy:NSURLRequestReloadIgnoringCacheData
                                     timeoutInterval:5.0];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request
                                                      delegate:self];

NSHTTPURLResponse* response = nil;
NSError* error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"statusCode = %d", [response statusCode]);

if ([response statusCode] == 404)
    NSLog(@"MISSING");
else
    NSLog(@"EXISTS");

响应总是 200,即使我重命名服务器上的文件。

4

2 回答 2

2

您的代码存在几个潜在问题。首先,当您conn使用创建时,connectionWithRequest:delegate:您正在启动一个异步请求。响应将在委托的(self在您的情况下)connection:didReceiveResponse:方法中收到。您是否尝试异步执行请求?但是,从您的其余代码看来,您实际上是在尝试执行同步请求。这sendSynchronousRequest:returningResponse:error:就是为了。如果这是您想要的,那么您不需要更早的调用来创建连接。

假设是这种情况,您需要捕获并检查从调用返回的值sendSynchronousRequest:returningResponse:error:。如果连接失败,它将返回 nil,这是我怀疑正在发生的事情。然后,您可以查看返回的错误以了解发生了什么。尝试类似:

NSData * result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if (result != nil) {
   NSLog(@"statusCode = %d", [response statusCode]);

   if ([response statusCode] == 404)
    NSLog(@"MISSING");
   else
       NSLog(@"EXISTS");
} else {
  NSLog(@"%@", error);
}
于 2010-08-27T20:47:43.447 回答
1

是否有可能在服务器端缓存?如果是这样,您可以尝试NSURLRequestReloadIgnoringLocalAndRemoteCacheData代替NSURLRequestReloadIgnoringCacheData.

于 2010-08-27T20:51:03.703 回答