Accessing HTTP Headers From An NSURLRequest

Rudi Farkas left this comment on my tutorial demonstrating how to use JSON over HTTP on the iPhone:

I would like to get to the HTTP headers that accompanied the response to a query sent via NSURLRequest.

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]);
	}
}

Updated based on Ben’s comment. See below for details.


© 2008-2011 • Mobile Orchard and the Bar-Tree Logo are service marks.