How to get HTTP headers

Nagra picture Nagra · Nov 5, 2012 · Viewed 32.9k times · Source

How do you retrieve all HTTP headers from a NSURLRequest in Objective-C?

Answer

Harish picture Harish · Nov 5, 2012

This falls under the easy, but not obvious class of iPhone programming problems. Worthy of a quick post:

The headers for an HTTP connection are included in the NSHTTPURLResponse class. If you have an NSHTTPURLResponse variable you can easily get the headers out as a NSDictionary by sending the allHeaderFields message.

For synchronous requests — not recommended, because they block — it’s easy to populate an NSHTTPURLResponse:

NSURL *url = [NSURL URLWithString:@"http://www.mobileorchard.com"];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [response allHeaderFields];
NSLog([dictionary description]);
}

With an asynchronous request you have to do a little more work. When the callback connection:didReceiveResponse: is called, it is passed an NSURLResponse as the second parameter. You can cast it to an NSHTTPURLResponse like so:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;    
if ([response respondsToSelector:@selector(allHeaderFields)]) {
    NSDictionary *dictionary = [httpResponse allHeaderFields];
    NSLog([dictionary description]);
}
}