0

I want to know the content_type of the NSURLRequest before it is downloaded.

As much as I searched I found the below code as solution :

NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *httpRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[httpRequest setHTTPMethod:@"HEAD"];
[httpRequest addValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:httpRequest
                                                completionHandler:
                                      ^(NSData *data, NSURLResponse *response, NSError *error) {
    NSHTTPResponse *httpResponse = (NSHTTPResponse*)response;                                  
    NSDictionary *dictionary = [httpResponse allHeaderFields];
    NSLog([dictionary[@"Content_Type"] description]);
}];
[task resume];

But i am always getting the content_type as text/HTML, even if the URL points to an image. So it might be the content_type of the header which send because of HEAD set at setHTTPMethod:@"HEAD".

Please help me to find the actual Content_Type of the NSURLRequest before downloading it.

Jeba Moses
  • 809
  • 8
  • 25
  • Can't you change the HTTP method to GET? why do you get with HEAD? – maty_nz Jan 18 '17 at 15:44
  • Did you check the result code when you checked the response? If you are not getting a 204 response, you would get a text/HTML body with some error text. Drop setting the Accept-Encoding header and see if that solves it for you. – David C. Nelson Jan 18 '17 at 19:16
  • @maty_nz am using HEAD to avoid downloading of entire content. My objective is to check the "Content_Type" so just for doing this i don't want to download the entire content.(It will increase execution time and duplication of downloading process). – Jeba Moses Jan 19 '17 at 05:42
  • @DavidC.Nelson The data(**NSData *data**) or result is empty. Also i already tried without `[httpRequest addValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];` . but the result is same. **Text/Html**. – Jeba Moses Jan 19 '17 at 05:44
  • Did you check the value of `[httpResponse statusCode]`? Another option to try is to do a GET and request only the first byte of the file. To do that, add a `Range` header with the value `"bytes=0-1"`. – David C. Nelson Jan 19 '17 at 20:12
  • @DavidC.Nelson i will try with **Range** attribute and let you know. – Jeba Moses Jan 20 '17 at 03:24

0 Answers0