iOS 快速只获取Http响应头
有些时候需要某个Http的响应头不需要响应文件
如对于一个.mp4的连接怎么快速获取文件大小或者是否经过了302跳转等。
//代码开始时间和结束时间
#define TICK NSDate *startTime = [NSDate date]
#define TOCK NSLog(@"__func__%s \r\n", __func__);\
NSLog(@"code runing Time duration : %f", -[startTime timeIntervalSinceNow]);\
NSLog(@"\n");
//这样获取的是全部文件 下面给出正确方案
NSURL *url = [NSURL URLWithString:@"/videofiles/20121214/9533522808.f4v.mp4"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
= @"GET";
//[request setHTTPMethod:@"HEAD"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
= NSURLRequestReloadIgnoringLocalCacheData;
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:[NSOperationQueue currentQueue]];
NSURLSessionDataTask *task = [urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
TOCK;
NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
NSDictionary *allHeaderFields = ;
TOCK;
if ([ containsString:urlStr] == NO) {
NSLog(@"302");
}
if ([ containsObject:@"Content-Length"]) {
NSNumber *lengthObj = [allHeaderFields objectForKey:@"Content-Length"];
//fileLength = [lengthObj integerValue];
}
NSLog(@"allHeaderFields is %@", allHeaderFields);
}];
[task resume];
//正确的只获取视频文件的响应头
TICK;
NSURL *url = [NSURL URLWithString:@"/videofiles/20121214/9533522808.f4v.mp4"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//只获取响应头 大概100ms就能返回
[request setHTTPMethod:@"HEAD"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
= NSURLRequestReloadIgnoringLocalCacheData;
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:[NSOperationQueue currentQueue]];
NSURLSessionDataTask *task = [urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
TOCK;
NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
NSDictionary *allHeaderFields = ;
if ([ containsString:urlStr] == NO) {
NSLog(@"302");
}
if ([ containsObject:@"Content-Length"]) {
NSNumber *lengthObj = [allHeaderFields objectForKey:@"Content-Length"];
//fileLength = [lengthObj integerValue];
}
NSLog(@"allHeaderFields is %@", allHeaderFields);
}];
[task resume];