I want to get only the headers of an URL request. I have been using stringWithContentsOfURL() for all downloading so far, but now I am only interested in the headers and downloading the entire file is not feasible as it is too large.
I have found solutions which show how to read the headers after the response has been receieved, but how do I specify in the request that I only wish to download headers. Skip the body!
Thanks.
Asynchronously send a HEAD request to the URL in question and then just access the allHeaderFields
property on HTTPURLResponse
/ NSHTTPURLResponse
.
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()
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];
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With