Get HTTP header fields only on iPhone

2020-02-29 06:56发布

问题:

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.

回答1:

What I've 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:

Asynchronously send a HEAD request to the URL in question and then just access the allHeaderFields property on 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];
                       }];


回答3:

only implement didReceiveResponse delegate method

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