如何让NSURLSession从服务器返回Content-Length(http头)。 Objective-c,ios

我花了好几个小时试着在这个问题的post中发现的各种想法没有成功。 当我使用curl时,我得到所需的标题 :Content-Length。

这是我最近的尝试(在SO上find的):

- (void) trythis { NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:myURL]; request.HTTPMethod = @"HEAD"; NSURLSessionDownloadTask *uploadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *url,NSURLResponse *response,NSError *error) { NSLog(@"handler size: %lld", response.expectedContentLength); NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; NSDictionary* headers = [httpResponse allHeaderFields]; NSArray *keys = [headers allKeys]; for( NSString *key in keys){ NSLog(@"key: %@ : %@", key, [headers valueForKey:key]); } NSLog(@""); }]; // 5 [uploadTask resume]; } 

它返回这些标题:

key:Vary:Accept-Encoding,User-Agent key:Server:Apache / 2.4.12 key:Connection:Keep-Alive key:Last-Modified:Sat,13 Jun 2015 23:03:46 GMT key:Content-Type:audio/ mpeg键:接受范围:字节键:date:2016年4月12日星期二17:59:21 GMT键:内容编码:gzip

使用curl(在macbook上)我得到:

curl -I http://boulderhomegrown.com/fiddletunes/JerusalemRidge-100.mp3

HTTP / 1.1 200 OKdate:2016年4月12日(日)14:55:17 GMT服务器:Apache / 2.4.12最后修改时间:2015年六月13日(星期六)23:03:46 GMT ETag:“2ec0bc0-1a172e-5186e3ca6b55f”接受-Ranges:bytes Content-Length:1709870 Vary:Accept-Encoding,User-Agent Content-Type:audio / mpeg

注意内容长度! 而且,当然,这两个url都是一样的。 这是我的objective-c中的一个实例variables。

默认情况下,你发送的请求有头 – 接受编码:gzip,deflate和服务器apache在这种情况下不添加头content-length(默认为较大的文件)。 所以,如果你用价值:身份代替头。 它将提供正确的文件大小。

这里是代码:

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:myURL]; request.HTTPMethod = @"HEAD"; [request addValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"]; 

只需要添加该字段,你将在响应像curl我有正确的头。