使用 NSURLConnection sendSynchronousRequest 时如何检查数据完整性?
我使用 NSURLConnection 类的 sendSynchronousRequest:returningResponse:error 方法从网络获取 NSData。
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]);
但不知道是否足以保证返回数据的完整性。 我无法检查远程服务器上文件的校验和。
您能分享一下您的经验或其他技巧吗?
谢谢。
I use sendSynchronousRequest:returningResponse:error method of NSURLConnection class to get NSData from network.
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
What I want to do is to check if returned value is valid or not.
So, what I did was to compare the length of the data with expected length in response header as below.
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]);
However, I don't know if it is enough to ensure the integrity of returned data.
I can't check checksum of the file on the remote server.
Can you share your experience or other tips?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在类中创建两个变量来存储当前下载的数据长度和预期数据的长度(您可以做得更优雅)
要知道预期数据的长度,您必须从 didReceiveResponse 委托获取它
以更新 downloadLenght,您必须在 didReceiveData: 中增加它:
然后可以在connectionDidFinishLoading中执行任何逻辑来比较下载的数据是否符合您的要求
我必须这样做来修复下载不完整的大图片的HJCache库问题(在HJMOHandler中)。
Create two variables in the class to store the length of data currently downloaded and the length of data expected (you could do more elegant)
To know the lenght of expected data you have to get it from didReceiveResponse delegate
to update the downloadedLenght, you have to increase it in didReceiveData:
then it is possible to do any logic to compare if downloaded data fit your requirements in connectionDidFinishLoading
I had to do this to fix HJCache library issues with big pictures that downloaded incomplete (in HJMOHandler).