使用NSURLConnection sendSynchronousRequest时如何检查数据完整性?

时间:2012-01-17 05:54:33

标签: nsurlconnection nsdata nsurlrequest integrity

我使用sendSynchronousRequest:returningResponse:NSURLConnection类的错误方法从网络获取NSData。

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]);

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

您可以分享您的经验或其他提示吗?

感谢。

1 个答案:

答案 0 :(得分:2)

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

int downloadedLength;
int expectedLength;

要了解预期数据的长度,您必须从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;
    }
}

我必须这样做才能解决HJCache库问题与下载不完整的大图片(在HJMOHandler中)。