Retrieve HTTP header fields on iPhone only

I want to get only URL request headers. I use stringWithContentsOfURL () so far for all downloads, but now I am only interested in the headers, and downloading the whole file is not possible because it is too large.

I found solutions that show how to read the headers after receiving the response, but how to indicate in the request that I only want to download the headers. Skip the body!

Thanks.

+4
source share
3 answers

What i used. The code below is synchronous, but you can make it asynchronous using a delegate.

NSMutableURLRequest *newRequest = ... //init your request... NSURLResponse *response=nil; NSError *error=nil; [newRequest setValue:@"HEAD" forKey:@"HTTPMethod"]; [NSURLConnection sendSynchronousRequest:newRequest returningResponse:&response error:&error]; [newRequest release]; //Get MIME type from the response NSString* MIMEType = [response MIMEType]; 

Edited to add replace NSURLRequest with NSMutableRequest.

+2
source

Asynchronously send a HEAD request to the URL in question, and then simply access the allHeaderFields property in HTTPURLResponse / NSHTTPURLResponse .

Swift 4

 var request = URLRequest(url: URL(string: "https://google.com/")!) request.httpMethod = "HEAD" let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let response = response as? HTTPURLResponse, let headers = response.allHeaderFields as? [String: String] else { return } } task.resume() 

Objective-c

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; [request setHTTPMethod:@"HEAD"]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; }]; 
+7
source

only implement didReceiveResponse delegation method

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSInteger statusCode = [(NSHTTPURLResponse*)response statusCode]; } 
+2
source

Source: https://habr.com/ru/post/1305823/


All Articles