Search code examples
ioshttphead

How to get NSURLSession to return Content-Length(http header) from server. Objective-c, ios


I have spend many hours trying the various ideas found in posts on this question with no success. When I use curl I get the desired header: Content-Length.

Here is my latest attempt(found somewhere on SO):

- (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];
}

It returns these headers:

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 key: Accept-Ranges : bytes key: Date : Tue, 12 Apr 2016 17:59:21 GMT key: Content-Encoding : gzip

Using curl (on macbook) I get:

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

HTTP/1.1 200 OK Date: Tue, 12 Apr 2016 14:55:17 GMT Server: Apache/2.4.12 Last-Modified: Sat, 13 Jun 2015 23:03:46 GMT ETag: "2ec0bc0-1a172e-5186e3ca6b55f" Accept-Ranges: bytes Content-Length: 1709870 Vary: Accept-Encoding,User-Agent Content-Type: audio/mpeg

NOTE the Content-Length!! And, of course, the url is the same in both. It's an instance variable in my objective-c.


Solution

  • By default the request you are sending has header - Accept-Encoding : gzip, deflate and the server apache in this case don't add the header content-length(by default for larger files). So if you replace that header with value: identity. It will provide the correct size of the file.

    Here is the code:

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

    Just have to add the field and you will have the right header in the response like curl -I does.