2012-01-17 72 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