2012-01-17 73 views
1

我使用sendSynchronousRequest:returningResponse:NSURLConnection类的错误方法从网络获取NSData。如何在使用NSURLConnection sendSynchronousRequest时检查数据完整性?

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html

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

我想要做的是检查返回值是否有效。 因此,我所做的是将响应头中的数据长度与期望长度进行比较,如下所示。

NSData *urlData; 
do { 
    urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    if ([urlData length] != [response expectedContentLength]) { 
     NSLog(@"WTF!!!!!!!!! NSURLConnection response[%@] length[%lld] [%d]", [[response URL] absoluteString], [response expectedContentLength], [urlData length]); 
     NSHTTPURLResponse *httpresponse = (NSHTTPURLResponse *) response; 
     NSDictionary *dic = [httpresponse allHeaderFields]; 
     NSLog(@"[%@]", [dic description]); 
    } 
} while ([urlData length] != [response expectedContentLength]); 

但是,我不知道是否足以确保返回的数据的完整性。 我无法检查远程服务器上文件的校验和。

你能分享你的经验或其他提示?

谢谢。

+0

您正在检查数据的长度,而不是完整性。根据完整性对您的重要性,您可以实施基于哈希的算法或更复杂的消息签名,或使用HTTPS。但无论如何,这需要一些服务器端的工作。客户端散列或签名消息,然后服务器检查。你提到你不能在服务器端这样做,所以不能保证完整性。 – 2012-03-20 16:21:19

回答

2

在类中创建两个变量来存储当前下载数据的长度和数据的预期(你可以做的更优雅)的长度

int downloadedLength; 
int expectedLength; 

知道预期的数据的lenght你必须得到它从didReceiveResponse代表

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ 

// NSLog(@"expected: %lld",response.expectedContentLength); 
    expectedLength = response.expectedContentLength; 
    downloadedLength = 0; 
} 

更新downloadedLenght,你必须增加它在didReceiveData:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
downloadedLength = downloadedLength + [data length]; 
//...some code 
} 

则是可能的,如果下载的数据符合您的要求,connectionDidFinishLoading

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

    if (downloadedLength == expectedLength) { 
     NSLog(@"correctly downloaded"); 
    } 
    else{ 
     NSLog(@"sizes don't match"); 
     return; 
    } 
} 

我不得不这样做是为了解决与下载的不完整的(在HJMOHandler)大图HJCache库的问题做任何逻辑比较。

+0

我遇到了这个确切的问题,这个确切的库。只是想表示感谢明确拼写出来。 – mousebird 2012-04-14 00:17:50